import { useCallback } from 'react';
import { useLocation } from 'react-router';
import { Unplug } from 'lucide-react';
import { usePanelChannel } from 'hooks/usePanelChannel';
import { useAuth } from 'hooks/useAuth';
import { useClaudeSessions } from 'state/useClaudeSessions';
import { useChat, EmbeddableChat } from '../Chat';
import type { ChatMessage } from '../Chat/types';

export type SelectedSession = {
  id: string;
  model?: string | null;
  resumeSummary?: string;
  resumeSessionId?: string;
  initialMessages?: ChatMessage[];
} | null;

const CHANNEL = 'chat:selected-session';

type ChatLocationState = {
  initialMessage?: string;
  prefillInput?: string;
  model?: string;
  cwd?: { root?: string; path: string };
  attachmentIds?: string[];
  images?: { filename: string; dataUrl: string }[];
} | null;

type DetailBarProps = {
  sessionTitle: string | undefined;
  isConnected: boolean;
  isGenerating: boolean;
  onDisconnect?: () => void;
};

function DetailBar({ sessionTitle, isConnected, isGenerating, onDisconnect }: DetailBarProps) {
  return (
    <div className="shrink-0 flex items-center px-4 py-2 border-b border-duck-dark/10 dark:border-foreground/10 bg-background/60">
      <div className="flex-1 min-w-0 text-center text-sm font-medium text-duck-dark/70 dark:text-foreground/70 truncate px-3">
        {sessionTitle ?? 'New chat'}
      </div>
      <div className="flex items-center gap-2 text-xs text-duck-dark/50 dark:text-foreground/50">
        {!isConnected ? (
          <span className="inline-block h-2 w-2 rounded-full bg-red-500" />
        ) : isGenerating ? (
          <span className="inline-block h-2 w-2 rounded-full bg-duck-orange animate-pulse" />
        ) : (
          <span className="inline-block h-2 w-2 rounded-full bg-green-500" />
        )}
        <span>{!isConnected ? 'Disconnected' : isGenerating ? 'Working...' : ''}</span>
        {isConnected && onDisconnect && (
          <button
            type="button"
            onClick={onDisconnect}
            title="End session — kills any running turn and releases it so it can be resumed elsewhere"
            className="ml-1 p-1 rounded hover:bg-duck-dark/10 dark:hover:bg-foreground/10 hover:text-red-500 transition-colors cursor-pointer"
          >
            <Unplug className="h-3.5 w-3.5" />
          </button>
        )}
      </div>
    </div>
  );
}

type NewChatProps = {
  resumeSummary?: string;
  resumeSessionId?: string;
  initialMessages?: ChatMessage[];
};

function NewChat({ resumeSummary, resumeSessionId, initialMessages }: NewChatProps) {
  const location = useLocation();
  const locationState = location.state as ChatLocationState;
  const { invalidate: invalidateClaudeSessions } = useClaudeSessions();

  // Refresh the /chat list — Claude has just written/appended this session's transcript.
  const onTurnComplete = useCallback(() => {
    invalidateClaudeSessions();
  }, [invalidateClaudeSessions]);

  // context 'chat' tells the backend to run this session from the dedicated general_chat_sessions cwd, so
  // its transcript lands in Claude's own store as an isolated project group (source of truth).
  const chat = useChat(undefined, locationState?.model, {
    resumeSummary,
    resumeSessionId,
    initialMessages,
    onTurnComplete,
    context: 'chat',
  });

  // Run the session in the pwd chosen in the Sessions panel; null → backend default (general_chat_sessions).
  const [activeCwd] = usePanelChannel<string | null>('chat:active-cwd', null);
  const cwd = activeCwd ? { path: activeCwd } : locationState?.cwd;

  const initialMessage = locationState?.initialMessage
    ? {
        text: locationState.initialMessage,
        attachmentIds: locationState.attachmentIds,
        images: locationState.images,
        cwd: locationState.cwd,
      }
    : undefined;

  return (
    <div className="flex flex-col h-full">
      <DetailBar sessionTitle={undefined} isConnected={chat.isConnected} isGenerating={chat.isGenerating} onDisconnect={chat.disconnectSession} />
      <EmbeddableChat
        chat={chat}
        sessionId={undefined}
        initialModel={locationState?.model ?? undefined}
        initialMessage={initialMessage}
        defaultInput={locationState?.prefillInput ?? ''}
        cwd={cwd}
        className="flex-1 min-h-0"
      />
    </div>
  );
}

export const ChatDetailPanel = () => {
  const [selected] = usePanelChannel<SelectedSession>(CHANNEL, null);

  if (!selected) {
    return (
      <div className="h-full flex items-center justify-center text-duck-dark/30 dark:text-foreground/30 text-sm">
        Select a session to view
      </div>
    );
  }

  return (
    <NewChat
      key={selected.id}
      resumeSummary={selected.resumeSummary}
      resumeSessionId={selected.resumeSessionId}
      initialMessages={selected.initialMessages}
    />
  );
};
