'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import { useSearchParams } from 'next/navigation';
import { getAgent, getConversation, getMessages } from '../../../lib/db';
import type { Agent, Conversation, Message } from '../../../lib/types';
import { ConversationView } from '../../components/ConversationView';

export default function ConversationPage({ params }: { params: { id: string } }) {
  const searchParams = useSearchParams();
  const [conversation, setConversation] = useState<Conversation | null>(null);
  const [agent, setAgent] = useState<Agent | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const load = async () => {
      const row = await getConversation(params.id);
      if (!row) {
        setLoading(false);
        return;
      }
      const msgRows = await getMessages(params.id, { limit: 200 });
      const agentRow = row.agentId ? await getAgent(row.agentId) : undefined;
      setConversation(row);
      setAgent(agentRow || null);
      setMessages(msgRows);
      setLoading(false);
    };
    void load();
  }, [params.id]);

  if (loading) {
    return <div className="p-6 text-sm text-[var(--text-secondary)]">Loading conversation...</div>;
  }

  if (!conversation) {
    return (
      <div className="p-6">
        <h1 className="text-lg font-semibold text-[var(--text-primary)]">Conversation not found</h1>
        <p className="mt-2 text-sm text-[var(--text-secondary)]">
          The conversation may have been deleted.
        </p>
        <Link
          href="/"
          className="mt-4 inline-block text-sm text-[var(--accent-primary)] hover:underline"
        >
          Back to workspace
        </Link>
      </div>
    );
  }

  return (
    <ConversationView
      conversation={conversation}
      initialMessages={messages}
      initialTemplate={searchParams.get('template') || ''}
      agent={agent || undefined}
    />
  );
}
