import { useState, useRef, useEffect, useCallback } from 'react';
import { Sparkles, MessageSquare, ArrowUp, Loader2, CheckCircle2 } from 'lucide-react';
import { trpc } from '@/lib/trpc';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { ChatMarkdown } from '@/components/ai/AIChatPanel';

export function PromptBuilderChat({
  agentType,
  dataTypes,
  directory,
  autoStart = false,
  onPromptUpdate,
  onConfigUpdate,
}: {
  agentType: 'local_directory' | 'gmail' | 'teams' | 'outlook';
  dataTypes: string[];
  directory?: string;
  autoStart?: boolean;
  onPromptUpdate?: (prompt: string) => void;
  onConfigUpdate?: (config: Record<string, unknown>) => void;
}) {
  const startMutation = trpc.agent.journey.start.useMutation();
  const messageMutation = trpc.agent.journey.message.useMutation();

  const [started, setStarted] = useState(false);
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [messages, setMessages] = useState<{ role: 'user' | 'assistant'; content: string }[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isDone, setIsDone] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  const handleStart = useCallback(() => {
    setStarted(true);
    setIsLoading(true);
    startMutation.mutate(
      { agentType, dataTypes, directory },
      {
        onSuccess: (res) => {
          if (res.data) {
            setSessionId(res.data.sessionId);
            const msgs: { role: 'user' | 'assistant'; content: string }[] = [];
            if (res.data.message.trim()) msgs.push({ role: 'assistant', content: res.data.message });
            if (res.data.done && res.data.agentConfig) {
              try {
                const parsed = JSON.parse(res.data.agentConfig) as Record<string, unknown>;
                onConfigUpdate?.(parsed);
              } catch { /* ignore parse errors */ }
              onPromptUpdate?.(res.data.agentConfig);
              setIsDone(true);
              msgs.push({ role: 'assistant', content: 'Your extraction config has been saved.' });
            }
            setMessages(msgs);
          }
          setIsLoading(false);
        },
        onError: () => {
          setMessages([{
            role: 'assistant',
            content: "Hi! I'll help you craft the perfect extraction prompt. What kind of information should this agent pull from your files?",
          }]);
          setIsLoading(false);
        },
      },
    );
  }, [agentType, dataTypes, directory, onConfigUpdate, onPromptUpdate, startMutation]);

  useEffect(() => {
    if (autoStart) handleStart();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  function handleSend() {
    if (!input.trim() || isLoading) return;
    const userMsg = input.trim();
    setInput('');
    setMessages(prev => [...prev, { role: 'user', content: userMsg }]);
    setIsLoading(true);

    messageMutation.mutate(
      { sessionId: sessionId ?? '', message: userMsg },
      {
        onSuccess: (res) => {
          if (res.data) {
            if (res.data.done && res.data.agentConfig) {
              try {
                const parsed = JSON.parse(res.data.agentConfig) as Record<string, unknown>;
                onConfigUpdate?.(parsed);
              } catch { /* ignore parse errors */ }
              onPromptUpdate?.(res.data.agentConfig);
              setIsDone(true);
            }
            const toAdd: { role: 'user' | 'assistant'; content: string }[] = [];
            if (res.data.message.trim()) toAdd.push({ role: 'assistant', content: res.data.message });
            if (res.data.done) toAdd.push({ role: 'assistant', content: 'Your extraction config has been saved.' });
            if (toAdd.length) setMessages(prev => [...prev, ...toAdd]);
          } else {
            setMessages(prev => [...prev, { role: 'assistant', content: 'Something went wrong. Please try again.' }]);
          }
          setIsLoading(false);
        },
        onError: () => {
          setMessages(prev => [...prev, { role: 'assistant', content: 'Could not reach backend. Check your connection.' }]);
          setIsLoading(false);
        },
      },
    );
  }

  if (!started) {
    return (
      <div className="rounded-2xl border border-dashed border-border/60 px-6 py-8 flex flex-col items-center gap-3 text-center">
        <div className="flex items-center justify-center size-10 rounded-full bg-primary/10">
          <Sparkles className="size-4 text-primary" />
        </div>
        <div>
          <p className="text-sm font-medium">Build your extraction prompt with AI</p>
          <p className="text-xs text-muted-foreground mt-1">A short conversation to tailor what your agent looks for.</p>
        </div>
        <Button size="sm" onClick={handleStart} className="mt-1">
          <MessageSquare className="size-3.5 mr-1.5" />
          Start prompt builder
        </Button>
      </div>
    );
  }

  return (
    <div className="flex flex-col gap-2 h-full">
      <div className="flex flex-col flex-1 min-h-0 overflow-hidden">
        <ScrollArea className="flex-1 min-h-0 h-full">
          <div className="p-4 flex flex-col gap-3">
            {messages.map((msg, i) =>
              msg.role === 'assistant' ? (
                <div key={i} className="flex items-start gap-2.5">
                  <div className="flex items-center justify-center size-6 rounded-full bg-primary/10 shrink-0 mt-0.5">
                    <Sparkles className="size-3 text-primary" />
                  </div>
                  <div className="min-w-0 flex-1">
                    <ChatMarkdown content={msg.content} />
                  </div>
                </div>
              ) : (
                <div key={i} className="flex justify-end">
                  <div className="ml-auto max-w-[75%] rounded-2xl bg-muted px-3.5 py-2">
                    <p className="text-sm">{msg.content}</p>
                  </div>
                </div>
              )
            )}
            {isLoading && (
              <div className="flex items-start gap-2.5">
                <div className="flex items-center justify-center size-6 rounded-full bg-primary/10 shrink-0 mt-0.5">
                  <Loader2 className="size-3 text-primary animate-spin" />
                </div>
                <p className="text-sm text-muted-foreground">Thinking...</p>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>
        </ScrollArea>
        <div className="p-3 shrink-0">
          <div className="relative rounded-xl bg-background/70 backdrop-blur-xl border border-border/50 shadow-sm ring-1 ring-border/20 transition-shadow focus-within:border-ring/50">
            <div className="flex items-center gap-2 px-3.5 py-2">
              <textarea
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }}
                placeholder="Describe what to extract..."
                rows={1}
                disabled={isLoading}
                className="flex-1 resize-none bg-transparent text-sm placeholder:text-muted-foreground outline-none max-h-[5rem] overflow-y-auto disabled:opacity-50"
                style={{ fieldSizing: 'content' } as React.CSSProperties}
              />
              <button
                onClick={handleSend}
                disabled={!input.trim() || isLoading}
                className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-primary text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-95 disabled:opacity-40 disabled:cursor-not-allowed"
              >
                <ArrowUp size={14} />
              </button>
            </div>
          </div>
        </div>
      </div>

      {isDone && (
        <div className="flex items-center gap-2 px-3.5 py-2.5 rounded-xl bg-primary/5 border border-primary/20">
          <CheckCircle2 className="size-4 text-primary shrink-0" />
          <p className="text-sm text-muted-foreground">Prompt saved — you can proceed to the next step or keep refining.</p>
        </div>
      )}
    </div>
  );
}
