"use client"

import { X, Sparkles } from "lucide-react"
import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sheet"
import { Button } from "@/components/ui/button"
import { AiChatIframe } from "@/components/ai/ai-chat-iframe"
import { useAiPanelStore } from "@/lib/ai/use-ai-panel"
import { useAiConfig, useAiQuota } from "@/lib/api/hooks/use-ai-queries"

export function AiChatPanel() {
  const open = useAiPanelStore((s) => s.open)
  const context = useAiPanelStore((s) => s.context)
  const closePanel = useAiPanelStore((s) => s.closePanel)
  const { data: config } = useAiConfig()
  const { data: quota } = useAiQuota(open && (config?.enabled ?? false))

  if (!config?.enabled) return null

  return (
    <Sheet open={open} onOpenChange={(v) => !v && closePanel()}>
      <SheetContent side="right" className="flex w-full flex-col gap-0 p-0 sm:max-w-xl">
        <SheetHeader className="flex flex-row items-center justify-between border-b px-4 py-3">
          <SheetTitle className="flex items-center gap-2 text-base">
            <Sparkles className="h-4 w-4 text-[#1a73e8]" />
            UltiAI
          </SheetTitle>
          <div className="flex items-center gap-2">
            {quota ? (
              <span className="text-xs text-muted-foreground">
                {quota.requests_remaining} req. restantes
              </span>
            ) : null}
            <Button variant="ghost" size="icon" onClick={closePanel} aria-label="Fermer">
              <X className="h-4 w-4" />
            </Button>
          </div>
        </SheetHeader>
        <AiChatIframe
          publicPath={config.public_path}
          context={context}
          className="h-full min-h-0 w-full flex-1 border-0"
        />
      </SheetContent>
    </Sheet>
  )
}
