import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { ArrowLeft } from 'lucide-react';
import type { Chat } from '@/api/types';
import { api } from '@/api/client';
import { useSessionStream } from '@/hooks/useSessionStream';
import { ChatPane } from '@/components/ChatPane';
import { DiffPane } from '@/components/DiffPane';
import { Layout } from '@/components/Layout';

export function Session() {
  const { sessionId } = useParams<{ sessionId: string }>();
  const navigate = useNavigate();
  const [chat, setChat] = useState<Chat | null>(null);
  const [loading, setLoading] = useState(true);

  const { messages, connected, isStreaming, onPendingChange } =
    useSessionStream(sessionId);

  // Get or create a chat for this session
  useEffect(() => {
    if (!sessionId) return;

    api.chats
      .listForSession(sessionId)
      .then((chats) => {
        // Use the first open chat, or create one
        const openChat = chats.find((c) => c.status === 'open');
        if (openChat) {
          setChat(openChat);
        } else {
          // Create a new chat
          return api.chats.create(sessionId).then((newChat) => {
            setChat(newChat);
          });
        }
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, [sessionId]);

  if (!sessionId) {
    navigate('/');
    return null;
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-zinc-900 flex items-center justify-center">
        <div className="text-zinc-500">Loading session...</div>
      </div>
    );
  }

  if (!chat) {
    return (
      <div className="min-h-screen bg-zinc-900 flex flex-col items-center justify-center gap-4">
        <div className="text-zinc-500">Could not load chat for this session.</div>
        <button
          onClick={() => navigate('/')}
          className="flex items-center gap-2 text-sm text-blue-400 hover:text-blue-300"
        >
          <ArrowLeft size={14} />
          Back to projects
        </button>
      </div>
    );
  }

  return (
    <Layout
      chatPane={
        <ChatPane
          sessionId={sessionId}
          chatId={chat.id}
          messages={messages}
          isStreaming={isStreaming}
          connected={connected}
        />
      }
      diffPane={
        <DiffPane sessionId={sessionId} onPendingChange={onPendingChange} />
      }
    />
  );
}
