'use client'

import { useMemo, useState } from 'react'
import { ClipboardCheck, Clock, CheckCircle2 } from 'lucide-react'
import {
  fetchSeoIssues,
  fetchSeoAuditRuns,
  type SeoIssue,
  type SeoIssueQuery,
  type SeoSeverity,
  type SeoIssueStatus,
} from '../../lib/seo-service.js'
import {
  SectionCard,
  SeoLoading,
  SeoEmptyState,
  SeoErrorState,
  severityMeta,
  SeoStatusBadge,
} from '../../components/seo/primitives.js'
import { SeoIssueFixDrawer } from '../../components/seo/SeoIssueFixDrawer.js'
import { useSeoResource } from './useSeoResource.js'

const SEVERITY_FILTERS: { id: SeoSeverity | 'all'; label: string }[] = [
  { id: 'all', label: 'All' },
  { id: 'critical', label: 'Critical' },
  { id: 'warning', label: 'Warnings' },
  { id: 'info', label: 'Info' },
]

const STATUS_FILTERS: { id: SeoIssueStatus | 'all'; label: string }[] = [
  { id: 'open', label: 'Open' },
  { id: 'recurring', label: 'Recurring' },
  { id: 'ignored', label: 'Ignored' },
  { id: 'resolved', label: 'Resolved' },
  { id: 'all', label: 'All' },
]

function issueStatusTone(status: SeoIssueStatus) {
  switch (status) {
    case 'resolved':
      return 'good' as const
    case 'ignored':
      return 'neutral' as const
    case 'recurring':
      return 'fair' as const
    default:
      return 'critical' as const
  }
}

function AuditSummaryCards({ refetchKey }: { refetchKey: number }) {
  const { data, loading } = useSeoResource(fetchSeoAuditRuns, [refetchKey])
  const last = (data ?? [])[0]
  return (
    <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
      <div className="border-border bg-card rounded-lg border p-4">
        <p className="text-muted-foreground flex items-center gap-1.5 text-sm">
          <Clock className="h-3.5 w-3.5" aria-hidden /> Last audit
        </p>
        <p className="text-foreground mt-1 text-sm font-medium">
          {loading ? '…' : last ? new Date(last.startedAt).toLocaleString() : 'Never'}
        </p>
      </div>
      <div className="border-border bg-card rounded-lg border p-4">
        <p className="text-muted-foreground text-sm">Pages scanned</p>
        <p className="text-foreground mt-1 text-2xl font-medium tabular-nums">
          {last?.pagesScanned ?? 0}
        </p>
      </div>
      <div className="border-border bg-card rounded-lg border p-4">
        <p className="text-muted-foreground text-sm">Issues found</p>
        <p className="text-foreground mt-1 text-2xl font-medium tabular-nums">
          {last?.issuesFound ?? 0}
        </p>
      </div>
      <div className="border-border bg-card rounded-lg border p-4">
        <p className="text-muted-foreground text-sm">Site score</p>
        <p className="text-foreground mt-1 text-2xl font-medium tabular-nums">
          {last?.siteScoreAfter ?? '—'}
        </p>
      </div>
    </div>
  )
}

export function AuditTab({
  refetchKey = 0,
  initialIssueId,
  onNavigate,
}: {
  refetchKey?: number
  initialIssueId?: string | null
  onNavigate?: (path: string) => void
}) {
  const [severity, setSeverity] = useState<SeoSeverity | 'all'>('all')
  const [status, setStatus] = useState<SeoIssueStatus | 'all'>('open')
  const [openIssue, setOpenIssue] = useState<string | null>(initialIssueId ?? null)

  const query: SeoIssueQuery = useMemo(() => ({ severity, status }), [severity, status])
  const { data, loading, error, refetch } = useSeoResource(
    () => fetchSeoIssues(query),
    [severity, status, refetchKey],
  )

  const issues = data ?? []

  return (
    <div className="space-y-4">
      <AuditSummaryCards refetchKey={refetchKey} />

      <SectionCard>
        <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex flex-wrap gap-1" role="group" aria-label="Filter by severity">
            {SEVERITY_FILTERS.map((f) => (
              <button
                key={f.id}
                type="button"
                aria-pressed={severity === f.id}
                onClick={() => setSeverity(f.id)}
                className={`focus-visible:ring-ring rounded-md px-3 py-1.5 text-sm font-medium transition-colors focus-visible:ring-2 focus-visible:outline-none ${
                  severity === f.id
                    ? 'bg-primary text-primary-foreground'
                    : 'text-muted-foreground hover:bg-accent hover:text-foreground'
                }`}
              >
                {f.label}
              </button>
            ))}
          </div>
          <div className="flex flex-wrap gap-1" role="group" aria-label="Filter by status">
            {STATUS_FILTERS.map((f) => (
              <button
                key={f.id}
                type="button"
                aria-pressed={status === f.id}
                onClick={() => setStatus(f.id)}
                className={`focus-visible:ring-ring rounded-md px-3 py-1.5 text-sm font-medium transition-colors focus-visible:ring-2 focus-visible:outline-none ${
                  status === f.id
                    ? 'bg-accent text-foreground'
                    : 'text-muted-foreground hover:bg-accent hover:text-foreground'
                }`}
              >
                {f.label}
              </button>
            ))}
          </div>
        </div>

        {loading ? (
          <SeoLoading label="Loading issues…" />
        ) : error ? (
          <SeoErrorState message={error} onRetry={refetch} />
        ) : issues.length === 0 ? (
          <SeoEmptyState
            icon={status === 'open' ? <CheckCircle2 size={24} /> : <ClipboardCheck size={24} />}
            title={status === 'open' ? 'No open issues' : 'No issues match'}
            description={
              status === 'open'
                ? 'Run an audit to scan for new issues, or adjust the filters.'
                : 'Try a different severity or status filter.'
            }
          />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm" aria-label="SEO issues">
              <thead>
                <tr className="text-muted-foreground border-border border-b text-left">
                  <th className="py-2 pr-4 font-medium">Severity</th>
                  <th className="py-2 pr-4 font-medium">Issue</th>
                  <th className="py-2 pr-4 font-medium">Page</th>
                  <th className="py-2 pr-4 font-medium">Status</th>
                  <th className="py-2 text-right font-medium">
                    <span className="sr-only">Actions</span>
                  </th>
                </tr>
              </thead>
              <tbody className="divide-border divide-y">
                {issues.map((issue: SeoIssue) => {
                  const meta = severityMeta(issue.severity)
                  return (
                    <tr key={issue.id} className="hover:bg-accent/40">
                      <td className="py-2.5 pr-4">
                        <span className={`inline-flex items-center gap-1.5 text-sm ${meta.text}`}>
                          <span className={`h-1.5 w-1.5 rounded-full ${meta.dot}`} aria-hidden />
                          {meta.label}
                        </span>
                      </td>
                      <td className="py-2.5 pr-4">
                        <span className="text-foreground block font-medium">{issue.title}</span>
                        <span className="text-muted-foreground block capitalize">
                          {issue.category}
                        </span>
                      </td>
                      <td className="text-muted-foreground py-2.5 pr-4">
                        <span className="block truncate">
                          {issue.entityTitle || issue.url || '—'}
                        </span>
                      </td>
                      <td className="py-2.5 pr-4">
                        <SeoStatusBadge label={issue.status} tone={issueStatusTone(issue.status)} />
                      </td>
                      <td className="py-2.5 text-right">
                        <button
                          onClick={() => setOpenIssue(issue.id)}
                          className="text-primary hover:bg-accent focus-visible:ring-ring rounded-md px-2 py-1 text-sm focus-visible:ring-2 focus-visible:outline-none"
                        >
                          {issue.fixable ? 'Fix' : 'View'}
                        </button>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>

      <SeoIssueFixDrawer
        open={openIssue !== null}
        onOpenChange={(o) => !o && setOpenIssue(null)}
        issueId={openIssue}
        onChanged={refetch}
        onNavigate={onNavigate}
      />
    </div>
  )
}
