import { useState, useEffect, useRef, useCallback } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useChatSettings } from '@/hooks/useSiteSettings';
import { ChatConversation } from '@/components/chat/ChatConversation';
import { PublicNavigation } from '@/components/public/PublicNavigation';
import { PublicFooter } from '@/components/public/PublicFooter';
import { Button } from '@/components/ui/button';
import { Plus, MessageSquare, Trash2 } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/hooks/useAuth';
import { cn } from '@/lib/utils';
import { ScrollArea } from '@/components/ui/scroll-area';

interface Conversation {
  id: string;
  title: string;
  created_at: string;
}

export default function ChatPage() {
  const navigate = useNavigate();
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const checkinId = searchParams.get('mode') === 'checkin' ? (searchParams.get('id') ?? undefined) : undefined;
  const { data: settings, isLoading: settingsLoading } = useChatSettings();
  const { user } = useAuth();
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [activeConversationId, setActiveConversationId] = useState<string | undefined>();
  const [chatKey, setChatKey] = useState(0);
  const [sidebarOpen, setSidebarOpen] = useState(true);
  
  // Get initial message from navigation state (from ChatLauncherBlock)
  const initialMessage = (location.state as { initialMessage?: string })?.initialMessage;
  const initialMessageProcessed = useRef(false);

  // Check if landing page is enabled
  useEffect(() => {
    if (!checkinId && !settingsLoading && !settings?.landingPageEnabled) {
      navigate('/');
    }
  }, [settings, settingsLoading, navigate, checkinId]);

  const loadConversations = useCallback(async () => {
    // /chat is the visitor surface — only show anonymous visitor threads
    // tied to this browser's session_id. Admin history lives in
    // /admin/flowchat (operator) and /admin/cowork (workspace Q&A).
    const sessionId = localStorage.getItem('chat-session-id');
    if (!sessionId) {
      setConversations([]);
      return;
    }
    const { data } = await supabase
      .from('chat_conversations')
      .select('id, title, created_at')
      .eq('scope', 'visitor')
      .eq('session_id', sessionId)
      .order('created_at', { ascending: false });
    if (data) setConversations(data);
  }, []);

  // Load conversations on mount
  useEffect(() => {
    loadConversations();
  }, [loadConversations]);

  const handleNewConversation = () => {
    localStorage.removeItem('chat-conversation-id');
    setActiveConversationId(undefined);
    setChatKey(k => k + 1);
  };

  const handleConversationCreated = (id: string) => {
    setActiveConversationId(id);
    // Reload immediately to show the new conversation
    loadConversations();
    // Reload again after a short delay so the title update from useChat has time to persist
    setTimeout(() => loadConversations(), 1500);
  };

  const handleDeleteConversation = async (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    // Clean up related data before deleting conversation
    await Promise.all([
      supabase.from('chat_messages').delete().eq('conversation_id', id),
      supabase.from('chat_feedback').delete().eq('conversation_id', id),
    ]);
    await supabase.from('chat_conversations').delete().eq('id', id);
    setConversations(prev => prev.filter(c => c.id !== id));
    if (activeConversationId === id) {
      setActiveConversationId(undefined);
    }
  };

  if (!checkinId && (settingsLoading || !settings?.landingPageEnabled)) return null;
  if (settingsLoading) return null;

  return (
    <div className="h-screen flex flex-col bg-background overflow-hidden">
      <PublicNavigation />
      {checkinId && (
        <div className="bg-primary/5 border-b px-4 py-2 text-sm text-center text-muted-foreground">
          ✦ Check-in mode — your profile will be updated
        </div>
      )}

      <main className="flex-1 flex min-h-0">
        {/* Sidebar */}
        <aside className={cn(
          'w-72 border-r bg-muted/30 flex flex-col transition-all flex-shrink-0',
          !sidebarOpen && 'w-0 overflow-hidden'
        )}>
          <div className="p-4 border-b">
            <Button
              onClick={handleNewConversation}
              className="w-full gap-2"
            >
              <Plus className="h-4 w-4" />
              New conversation
            </Button>
          </div>

          <ScrollArea className="flex-1">
            {conversations.length === 0 ? (
              <div className="p-4 text-xs text-muted-foreground text-center">
                Your conversations will appear here.
              </div>
            ) : (
              <div className="p-2 space-y-1">
                {conversations.map((conv) => (
                  <button
                    key={conv.id}
                    onClick={() => setActiveConversationId(conv.id)}
                    className={cn(
                      'w-full flex items-center gap-2 px-3 py-2 rounded-lg text-left text-sm',
                      'hover:bg-muted group transition-colors',
                      activeConversationId === conv.id && 'bg-muted'
                    )}
                  >
                    <MessageSquare className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
                    <span className="flex-1 truncate">{conv.title}</span>
                    <Button
                      variant="ghost"
                      size="icon"
                      className="h-6 w-6 opacity-0 group-hover:opacity-100"
                      onClick={(e) => handleDeleteConversation(conv.id, e)}
                    >
                      <Trash2 className="h-3 w-3" />
                    </Button>
                  </button>
                ))}
              </div>
            )}
          </ScrollArea>
        </aside>
        {/* Main chat area */}
        <div className="flex-1 flex flex-col min-h-0 min-w-0">
          <ChatConversation
            key={chatKey}
            mode="landing"
            conversationId={activeConversationId}
            onNewConversation={handleConversationCreated}
            skipRestore={chatKey > 0}
            className="flex-1 min-h-0"
            initialMessage={!initialMessageProcessed.current ? initialMessage : undefined}
            onInitialMessageSent={() => {
              initialMessageProcessed.current = true;
              navigate(location.pathname, { replace: true, state: {} });
            }}
            checkinId={checkinId}
          />
        </div>
      </main>
    </div>
  );
}
