import { useRef, useState, useCallback } from 'react';
import { useNavigate } from 'react-router';
import { Plus, MessageSquare, RefreshCw, Loader2, Trash2, Pencil, Check, X } from 'lucide-react';
import { usePanelChannel } from 'hooks/usePanelChannel';
import { useClaudeSessions } from 'state/useClaudeSessions';
import type { SelectedSession } from './ChatDetailPanel';
import type { ChatMessage } from '../Chat/types';
import { PwdSelector } from './PwdSelector';

// Reads the /chat conversation list from Claude's own transcript store (source of truth).
// Clicking a session loads its transcript and continues the real Claude session via --resume.
export const SessionList = () => {
  const navigate = useNavigate();
  // The working directory the list operates on (null = the default general_chat_sessions dir).
  const [activeCwd, setActiveCwd] = usePanelChannel<string | null>('chat:active-cwd', null);
  const { sessions, isLoading, refetch, loadSession, deleteSession, renameSession } = useClaudeSessions(activeCwd);
  const [selected, setSelected] = usePanelChannel<SelectedSession>('chat:selected-session', null);
  const [openingId, setOpeningId] = useState<string | null>(null);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editValue, setEditValue] = useState('');
  const [confirmingId, setConfirmingId] = useState<string | null>(null);

  const scrolledRef = useRef(false);
  const selectedRef = useCallback((node: HTMLDivElement | null) => {
    if (node && !scrolledRef.current) {
      scrolledRef.current = true;
      node.scrollIntoView({ block: 'center' });
    }
  }, []);

  const handleSelect = async (id: string) => {
    if (openingId || editingId) return;
    setOpeningId(id);
    try {
      const detail = await loadSession(id);
      setSelected({ id, model: detail.model, resumeSessionId: id, initialMessages: detail.messages as ChatMessage[] });
    } finally {
      setOpeningId(null);
    }
  };

  const startRename = (id: string, current: string) => {
    setConfirmingId(null);
    setEditingId(id);
    setEditValue(current);
  };

  const commitRename = async () => {
    const id = editingId;
    const title = editValue.trim();
    setEditingId(null);
    if (id && title) await renameSession(id, title);
  };

  const handleDelete = async (id: string) => {
    if (selected?.id === id) setSelected(null);
    setConfirmingId(null);
    await deleteSession(id);
  };

  return (
    <div className="flex flex-col h-full overflow-hidden">
      {/* Header */}
      <div className="shrink-0 flex items-center gap-2 px-3 py-2 border-b border-duck-dark/10 dark:border-foreground/10 bg-background/60">
        <PwdSelector
          value={activeCwd}
          onChange={(cwd) => {
            setActiveCwd(cwd);
            setSelected(null); // sessions belong to a cwd — clear the open one when switching
          }}
        />
        <div className="ml-auto flex items-center gap-1.5">
          <button
            onClick={() => refetch()}
            className="p-1 rounded text-duck-dark/40 dark:text-foreground/40 hover:text-duck-teal cursor-pointer transition-colors"
            title="Refresh"
          >
            <RefreshCw className={`h-3.5 w-3.5 ${isLoading ? 'animate-spin' : ''}`} />
          </button>
          <button
            onClick={() => {
              setSelected({ id: `new:${Date.now()}` });
              navigate('/chat/new', { replace: true });
            }}
            className="flex items-center gap-1.5 rounded-md bg-duck-teal hover:bg-duck-teal/90 text-duck-yellow cursor-pointer h-7 px-3 text-xs font-medium"
          >
            <Plus className="h-3.5 w-3.5" />
            New Chat
          </button>
        </div>
      </div>

      {/* Session list */}
      <div className="flex-1 min-h-0 overflow-y-auto p-3 space-y-1.5">
        {sessions.length === 0 && (
          <div className="text-center py-16 text-duck-dark/30 dark:text-foreground/30 text-sm">
            {isLoading ? 'Loading…' : 'No sessions yet. Start a new chat to see it here.'}
          </div>
        )}

        {sessions.map((session) => {
          const isActive = selected?.id === session.id;
          const isEditing = editingId === session.id;
          const isConfirming = confirmingId === session.id;
          return (
            <div
              key={session.id}
              ref={isActive ? selectedRef : undefined}
              className={`group flex items-center rounded-lg border transition-colors ${
                isActive
                  ? 'border-duck-teal/30 bg-duck-teal/5 dark:bg-duck-teal/10'
                  : 'border-duck-dark/10 dark:border-foreground/10 bg-background/80 hover:bg-background/90'
              }`}
            >
              {isEditing ? (
                <div className="flex flex-1 items-center gap-2 px-4 py-3 min-w-0">
                  <input
                    autoFocus
                    value={editValue}
                    onChange={(ev) => setEditValue(ev.target.value)}
                    onKeyDown={(ev) => {
                      if (ev.key === 'Enter') commitRename();
                      if (ev.key === 'Escape') setEditingId(null);
                    }}
                    onBlur={commitRename}
                    className="flex-1 min-w-0 bg-transparent border-b border-duck-teal/40 text-sm outline-none"
                  />
                  <button
                    onMouseDown={(ev) => ev.preventDefault()}
                    onClick={commitRename}
                    className="p-1 text-duck-teal hover:opacity-80 cursor-pointer"
                    title="Save"
                  >
                    <Check className="h-3.5 w-3.5" />
                  </button>
                  <button
                    onMouseDown={(ev) => ev.preventDefault()}
                    onClick={() => setEditingId(null)}
                    className="p-1 opacity-50 hover:opacity-100 cursor-pointer"
                    title="Cancel"
                  >
                    <X className="h-3.5 w-3.5" />
                  </button>
                </div>
              ) : (
                <>
                  <button
                    onClick={() => handleSelect(session.id)}
                    disabled={!!openingId}
                    className="flex flex-1 items-center gap-3 px-4 py-3 min-w-0 text-left cursor-pointer"
                  >
                    {openingId === session.id ? (
                      <Loader2 className="h-4 w-4 shrink-0 text-duck-teal/60 animate-spin" />
                    ) : (
                      <MessageSquare className="h-4 w-4 shrink-0 text-duck-teal/60" />
                    )}
                    <div className="min-w-0 flex-1">
                      <div className="text-sm font-medium text-duck-dark/80 dark:text-foreground/80 truncate">
                        {session.title}
                      </div>
                      <div className="flex items-center gap-2 text-xs text-duck-dark/40 dark:text-foreground/40">
                        <span>
                          {new Date(session.updatedAt).toLocaleDateString(undefined, {
                            month: 'short',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit',
                          })}
                        </span>
                        <span>·</span>
                        {session.harness === 'opencode' ? (
                          <span className="rounded bg-duck-teal/10 px-1.5 py-0.5 font-medium text-duck-teal">
                            OpenCode
                          </span>
                        ) : (
                          <span>
                            {session.messageCount} msg{session.messageCount === 1 ? '' : 's'}
                          </span>
                        )}
                      </div>
                    </div>
                  </button>

                  {isConfirming ? (
                    <div className="flex shrink-0 items-center gap-1 mr-2">
                      <span className="text-xs text-red-500">Delete?</span>
                      <button
                        onClick={() => handleDelete(session.id)}
                        className="p-1 rounded text-red-500 hover:bg-red-500/10 cursor-pointer"
                        title="Confirm delete"
                      >
                        <Check className="h-3.5 w-3.5" />
                      </button>
                      <button
                        onClick={() => setConfirmingId(null)}
                        className="p-1 rounded opacity-50 hover:opacity-100 cursor-pointer"
                        title="Cancel"
                      >
                        <X className="h-3.5 w-3.5" />
                      </button>
                    </div>
                  ) : (
                    <div className="flex shrink-0 items-center mr-2 opacity-0 group-hover:opacity-100 transition-opacity">
                      <button
                        onClick={() => startRename(session.id, session.title)}
                        className="p-1.5 rounded text-duck-dark/30 dark:text-foreground/30 hover:text-duck-teal cursor-pointer transition-colors"
                        title="Rename"
                      >
                        <Pencil className="h-3.5 w-3.5" />
                      </button>
                      <button
                        onClick={() => setConfirmingId(session.id)}
                        className="p-1.5 rounded text-duck-dark/30 dark:text-foreground/30 hover:text-red-500 cursor-pointer transition-colors"
                        title="Delete session"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </button>
                    </div>
                  )}
                </>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};
