"use client"

import { useEffect, useState, type CSSProperties } from "react"
import { Loader2, Sparkles } from "lucide-react"
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from "@/components/ui/dialog"
import type { Agent } from "@/lib/types"

interface AgentSelectorProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onAgentSelected: (agent: Agent) => void
}

export function AgentSelector({
  open,
  onOpenChange,
  onAgentSelected,
}: AgentSelectorProps) {
  const [agents, setAgents] = useState<Agent[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!open) return

    const fetchAgents = async () => {
      try {
        setIsLoading(true)
        setError(null)
        const response = await fetch("/api/agents")
        const data = (await response.json()) as { agents?: unknown; error?: string }

        if (!response.ok || !data.agents) {
          throw new Error(data.error || "Failed to load agents")
        }

        const agentsList = data.agents as typeof agents
        setAgents(agentsList)

        if (agentsList.length === 0) {
          setError("No agents configured. Please add agents via environment variables.")
        }
      } catch (err) {
        setError(
          err instanceof Error ? err.message : "Failed to load agents",
        )
      } finally {
        setIsLoading(false)
      }
    }

    fetchAgents()
  }, [open])

  useEffect(() => {
    if (!open) return
    const cards = document.querySelectorAll<HTMLElement>("[data-reveal='agent-card']")
    if (!cards.length) return

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add("is-visible")
            observer.unobserve(entry.target)
          }
        })
      },
      { threshold: 0.25 }
    )

    cards.forEach((card) => observer.observe(card))

    return () => observer.disconnect()
  }, [agents, open])

  const handleSelectAgent = (agent: Agent) => {
    // Store selected agent in localStorage
    localStorage.setItem("selected-agent-id", agent.id)
    localStorage.setItem("selected-agent", JSON.stringify(agent))
    // Close dialog and notify parent component
    onOpenChange(false)
    onAgentSelected(agent)
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-2xl border-none bg-transparent p-0 shadow-none">
        <div
          className="palette-shell"
          style={
            {
              "--panel-tint": "rgba(230, 126, 80, 0.25)",
            } as CSSProperties
          }
        >
          <DialogHeader>
            <div className="mb-4 flex justify-center">
              <div className="flex h-14 w-14 items-center justify-center rounded-full border border-border/40 bg-white/40 text-burnt shadow-md">
                <Sparkles className="h-6 w-6 text-burnt" />
              </div>
            </div>
            <DialogTitle className="text-center text-3xl font-heading">
              Select Your Correspondent
            </DialogTitle>
            <DialogDescription className="text-center text-base leading-relaxed text-muted-foreground">
              Each agent keeps a different archive. Take a breath, read their placard, then choose the voice you trust.
            </DialogDescription>
          </DialogHeader>

        {isLoading ? (
          <div className="flex justify-center py-8">
            <div className="text-center">
              <Loader2 className="mx-auto h-8 w-8 animate-spin text-burnt" />
              <p className="mt-2 text-sm text-muted-foreground">Cataloguing configured agents…</p>
            </div>
          </div>
        ) : error ? (
          <div className="rounded-lg border border-destructive/40 bg-destructive/15 p-4 text-center">
            <p className="text-sm text-destructive">{error}</p>
          </div>
        ) : (
          <div className="grid gap-4 py-6 md:grid-cols-2">
            {agents.map((agent, index) => (
              <button
                key={agent.id}
                onClick={() => handleSelectAgent(agent)}
                className="swatch-card scroll-reveal group p-5 text-left focus-visible:ring-2 focus-visible:ring-ring"
                data-reveal="agent-card"
                style={
                  {
                    animationDelay: `${index * 50}ms`,
                    "--swatch-color": index % 2 === 0 ? "var(--burnt-orange)" : "var(--terracotta)",
                  } as CSSProperties
                }
              >
                <div className="flex items-start justify-between">
                  <div>
                    <span className="eyebrow text-[0.65rem] text-muted-foreground">Agent</span>
                    <h3 className="mt-2 font-heading text-xl text-charcoal">{agent.name}</h3>
                  </div>
                  <div className="message-avatar assistant !h-9 !w-9 rounded-full text-[0.6rem] uppercase tracking-[0.25em]">
                    {agent.name.slice(0, 2)}
                  </div>
                </div>
                <p className="mt-3 text-sm leading-relaxed text-muted-foreground">
                  {agent.description}
                </p>
                <p className="mt-4 text-[0.65rem] uppercase tracking-[0.2em] text-muted-foreground">
                  Press enter to begin
                </p>
              </button>
            ))}
          </div>
        )}
        </div>
      </DialogContent>
    </Dialog>
  )
}
