"use client"

import Link from "next/link"
import { Sparkles } from "lucide-react"
import { AiChatIframe } from "@/components/ai/ai-chat-iframe"
import { useAiConfig, useAiQuota } from "@/lib/api/hooks/use-ai-queries"
import { Button } from "@/components/ui/button"

export default function ChatPage() {
  const { data: config, isLoading, isError } = useAiConfig()
  const { data: quota } = useAiQuota(Boolean(config?.enabled))

  if (isLoading) {
    return (
      <div className="flex h-dvh items-center justify-center text-sm text-muted-foreground">
        Chargement UltiAI…
      </div>
    )
  }

  if (isError) {
    return (
      <div className="flex h-dvh flex-col items-center justify-center gap-3 px-6 text-center">
        <Sparkles className="h-8 w-8 text-muted-foreground" />
        <p className="text-sm text-muted-foreground">
          Impossible de contacter l&apos;API UltiAI. Vérifiez que le backend est démarré.
        </p>
      </div>
    )
  }

  if (!config?.enabled) {
    return (
      <div className="flex h-dvh flex-col items-center justify-center gap-3 px-6 text-center">
        <Sparkles className="h-8 w-8 text-muted-foreground" />
        <p className="max-w-md text-sm text-muted-foreground">
          UltiAI n&apos;est pas activé. Activez le plugin{" "}
          <strong>UltiAI</strong> dans Administration → Plugins (puis enregistrez), ou définissez{" "}
          <code className="rounded bg-muted px-1">AI_ASSISTANT_ENABLED=true</code> dans le
          déploiement backend.
        </p>
        <Button asChild variant="outline" size="sm">
          <Link href="/admin/settings/plugins">Ouvrir les plugins</Link>
        </Button>
      </div>
    )
  }

  return (
    <div className="flex h-dvh flex-col">
      <header className="flex items-center justify-between border-b px-4 py-2">
        <div className="flex items-center gap-2 text-sm font-medium">
          <Sparkles className="h-4 w-4 text-[#1a73e8]" />
          UltiAI
        </div>
        {quota ? (
          <span className="text-xs text-muted-foreground">
            {quota.requests_remaining}/{quota.requests_limit} requêtes aujourd&apos;hui
          </span>
        ) : null}
      </header>
      <AiChatIframe
        publicPath={config.public_path}
        context={{ app: "standalone", temporary: false }}
        className="min-h-0 flex-1 border-0"
      />
    </div>
  )
}
