'use client'

import { useState } from 'react'
import { Sparkles, Bot } from 'lucide-react'
import { toast } from 'sonner'
import { summarizeSeoAudit } from '../../lib/seo-service.js'
import { Drawer } from './Drawer.js'
import { SeoLoading, SeoEmptyState, btnPrimary } from './primitives.js'

/**
 * AI Copilot drawer — summarizes the current SEO state and surfaces the top
 * priorities. Degrades gracefully when AI is unconfigured. All AI text is
 * advisory; the editor takes action via the tabs/drawers.
 */
export function SeoCopilotDrawer({
  open,
  onOpenChange,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
}) {
  const [loading, setLoading] = useState(false)
  const [summary, setSummary] = useState<string | null>(null)
  const [unavailable, setUnavailable] = useState(false)

  async function handleSummarize() {
    setLoading(true)
    setUnavailable(false)
    const res = await summarizeSeoAudit()
    setLoading(false)
    if (res.unavailable) {
      setUnavailable(true)
      return
    }
    if (res.text) setSummary(res.text)
    else toast.error('No summary was returned.')
  }

  return (
    <Drawer
      open={open}
      onOpenChange={onOpenChange}
      title="SEO Copilot"
      description="AI-assisted analysis of your site's SEO health"
      width="max-w-md"
      footer={
        <button className={btnPrimary} onClick={handleSummarize} disabled={loading}>
          <Sparkles className={`h-4 w-4 ${loading ? 'animate-pulse' : ''}`} aria-hidden />
          {loading ? 'Analyzing…' : summary ? 'Re-analyze' : 'Analyze my SEO'}
        </button>
      }
    >
      {loading ? (
        <SeoLoading label="Analyzing your SEO…" />
      ) : unavailable ? (
        <SeoEmptyState
          icon={<Bot size={24} />}
          title="AI is not configured"
          description="Install and configure an AI provider (plugin-ai) to enable the SEO Copilot."
        />
      ) : summary ? (
        <div className="text-foreground space-y-3 text-sm leading-relaxed">
          {summary.split(/\n+/).map((para, i) => (
            <p key={i}>{para}</p>
          ))}
        </div>
      ) : (
        <SeoEmptyState
          icon={<Bot size={24} />}
          title="Ask the Copilot"
          description="Get an AI summary of your open issues and the top priorities to fix first."
        />
      )}
    </Drawer>
  )
}
