'use client'

import { useEffect, useState } from 'react'
import { Sparkles, ArrowRight, ExternalLink, Image as ImageIcon, Gauge } from 'lucide-react'
import { toast } from 'sonner'
import {
  fetchSeoIssue,
  resolveSeoIssue,
  ignoreSeoIssue,
  reopenSeoIssue,
  explainSeoIssue,
  type SeoIssue,
} from '../../lib/seo-service.js'
import { Drawer } from './Drawer.js'
import { SeoLoading, SeoErrorState, severityMeta, btnPrimary, btnSecondary } from './primitives.js'

/** Map a fix action to a destination route within the admin. */
function fixRoute(issue: SeoIssue): { label: string; path: string; icon: React.ReactNode } | null {
  const ent = issue.entityType
  const id = issue.entityId
  switch (issue.fixActionType) {
    case 'edit-metadata':
    case 'edit-canonical':
    case 'edit-og':
    case 'edit-schema':
      if (ent && id) {
        return {
          label: 'Edit content SEO',
          path: `/seo?tab=content&entityType=${ent}&entityId=${encodeURIComponent(id)}`,
          icon: <ArrowRight className="h-4 w-4" aria-hidden />,
        }
      }
      return null
    case 'fix-broken-link':
    case 'create-redirect':
      return {
        label: 'Open redirects',
        path: '/seo?tab=redirects',
        icon: <ArrowRight className="h-4 w-4" aria-hidden />,
      }
    case 'optimize-media':
      return {
        label: 'Open Media Center',
        path: '/media',
        icon: <ImageIcon className="h-4 w-4" aria-hidden />,
      }
    case 'improve-speed':
      return {
        label: 'Technical settings',
        path: '/seo?tab=technical',
        icon: <Gauge className="h-4 w-4" aria-hidden />,
      }
    default:
      return null
  }
}

export function SeoIssueFixDrawer({
  open,
  onOpenChange,
  issueId,
  onChanged,
  onNavigate,
}: {
  open: boolean
  onOpenChange: (open: boolean) => void
  issueId: string | null
  onChanged?: () => void
  onNavigate?: (path: string) => void
}) {
  const [issue, setIssue] = useState<SeoIssue | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)
  const [explanation, setExplanation] = useState<string | null>(null)
  const [explaining, setExplaining] = useState(false)

  useEffect(() => {
    if (!open || !issueId) return
    let alive = true
    setLoading(true)
    setError(null)
    setExplanation(null)
    fetchSeoIssue(issueId)
      .then((i) => {
        if (!alive) return
        if (!i) setError('Issue not found.')
        else setIssue(i)
      })
      .catch((e) => alive && setError(e instanceof Error ? e.message : 'Failed to load'))
      .finally(() => alive && setLoading(false))
    return () => {
      alive = false
    }
  }, [open, issueId])

  async function mutate(fn: (id: string) => Promise<{ error?: string }>, successMsg: string) {
    if (!issue) return
    setBusy(true)
    const res = await fn(issue.id)
    setBusy(false)
    if (res.error) return toast.error(res.error)
    toast.success(successMsg)
    onOpenChange(false)
    onChanged?.()
  }

  async function handleExplain() {
    if (!issue) return
    setExplaining(true)
    const res = await explainSeoIssue(issue.id)
    setExplaining(false)
    if (res.unavailable) {
      toast.error('AI is not configured.')
      return
    }
    setExplanation(res.text ?? 'No explanation available.')
  }

  const route = issue ? fixRoute(issue) : null

  return (
    <Drawer
      open={open}
      onOpenChange={onOpenChange}
      title="Issue detail"
      width="max-w-lg"
      footer={
        issue ? (
          <>
            {issue.status === 'ignored' ? (
              <button
                className={btnSecondary}
                onClick={() => mutate(reopenSeoIssue, 'Issue reopened.')}
                disabled={busy}
              >
                Reopen
              </button>
            ) : (
              <button
                className={btnSecondary}
                onClick={() => mutate(ignoreSeoIssue, 'Issue ignored.')}
                disabled={busy}
              >
                Ignore
              </button>
            )}
            {route && onNavigate ? (
              <button
                className={btnPrimary}
                onClick={() => {
                  onNavigate(route.path)
                  onOpenChange(false)
                }}
              >
                {route.icon}
                {route.label}
              </button>
            ) : (
              <button
                className={btnPrimary}
                onClick={() => mutate(resolveSeoIssue, 'Issue resolved.')}
                disabled={busy}
              >
                Mark resolved
              </button>
            )}
          </>
        ) : null
      }
    >
      {loading ? (
        <SeoLoading />
      ) : error ? (
        <SeoErrorState message={error} />
      ) : issue ? (
        <div className="space-y-4">
          {(() => {
            const meta = severityMeta(issue.severity)
            return (
              <span
                className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-xs font-medium ${meta.bg} ${meta.text}`}
              >
                <span className={`h-1.5 w-1.5 rounded-full ${meta.dot}`} aria-hidden />
                {meta.label} · {issue.category}
              </span>
            )
          })()}

          <div>
            <h3 className="text-foreground text-base font-medium">{issue.title}</h3>
            {issue.entityTitle && (
              <p className="text-muted-foreground mt-0.5 text-sm">{issue.entityTitle}</p>
            )}
          </div>

          {issue.url && (
            <a
              href={issue.url}
              target="_blank"
              rel="noopener noreferrer"
              className="text-primary inline-flex items-center gap-1 text-sm hover:underline"
            >
              {issue.url}
              <ExternalLink className="h-3.5 w-3.5" aria-hidden />
            </a>
          )}

          {issue.description && <p className="text-foreground text-sm">{issue.description}</p>}

          {issue.impact && (
            <div className="border-border rounded-md border p-3">
              <p className="text-muted-foreground text-xs font-medium tracking-wide uppercase">
                Impact
              </p>
              <p className="text-foreground mt-1 text-sm">{issue.impact}</p>
            </div>
          )}

          {issue.recommendation && (
            <div className="border-border rounded-md border p-3">
              <p className="text-muted-foreground text-xs font-medium tracking-wide uppercase">
                Recommendation
              </p>
              <p className="text-foreground mt-1 text-sm">{issue.recommendation}</p>
            </div>
          )}

          <div className="border-border rounded-md border p-3">
            <button
              onClick={handleExplain}
              disabled={explaining}
              className="text-primary focus-visible:ring-ring inline-flex items-center gap-1.5 text-sm font-medium focus-visible:ring-2 focus-visible:outline-none disabled:opacity-60"
            >
              <Sparkles className={`h-4 w-4 ${explaining ? 'animate-pulse' : ''}`} aria-hidden />
              {explaining ? 'Asking AI…' : 'Explain with AI'}
            </button>
            {explanation && <p className="text-foreground mt-2 text-sm">{explanation}</p>}
          </div>
        </div>
      ) : null}
    </Drawer>
  )
}
