'use client'

import {
  TrendingUp,
  TrendingDown,
  Minus,
  AlertOctagon,
  AlertTriangle,
  Info,
  Zap,
  BarChart3,
  ArrowRight,
} from 'lucide-react'
import type { QuickWin, SeoMetric, SeoOverview } from '../../lib/seo-service.js'
import {
  SectionCard,
  SeoScoreBar,
  SeoLoading,
  SeoEmptyState,
  SeoErrorState,
  gradeMeta,
  btnSecondary,
} from '../../components/seo/primitives.js'
import type { SeoResource } from './useSeoResource.js'

function TrendIcon({ trend }: { trend?: SeoMetric['trend'] }) {
  if (trend === 'up') return <TrendingUp className="text-success h-4 w-4" aria-hidden />
  if (trend === 'down') return <TrendingDown className="text-destructive h-4 w-4" aria-hidden />
  return <Minus className="text-muted-foreground h-4 w-4" aria-hidden />
}

function impactTone(impact: QuickWin['impact']): 'good' | 'fair' | 'poor' {
  return impact === 'High' ? 'poor' : impact === 'Medium' ? 'fair' : 'good'
}

export function OverviewTab({
  resource,
  onOpenIssue,
  onConnectSearchConsole,
}: {
  resource: SeoResource<SeoOverview>
  onOpenIssue?: (issueId: string) => void
  onConnectSearchConsole?: () => void
}) {
  const { data, loading, error, refetch } = resource

  if (loading) return <SeoLoading label="Loading SEO overview…" />
  if (error) return <SeoErrorState message={error} onRetry={refetch} />
  if (!data) return <SeoEmptyState title="No overview data" />

  const {
    siteScore,
    metrics,
    issuesSummary,
    quickWins,
    searchPerformance,
    searchConsoleConnected,
  } = data
  const grade = gradeMeta(siteScore.grade)

  return (
    <div className="space-y-6">
      {/* Site score + metrics */}
      <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
        <SectionCard title="Site SEO Score" className="lg:col-span-1">
          <div className="flex items-center gap-4">
            <div className="flex flex-col">
              <span className="text-foreground text-4xl font-medium tabular-nums">
                {siteScore.score}
              </span>
              <span className={`text-sm font-medium ${grade.text}`}>{grade.label}</span>
            </div>
            {siteScore.delta !== null && (
              <span
                className={`inline-flex items-center gap-1 text-sm ${
                  siteScore.delta >= 0 ? 'text-success' : 'text-destructive'
                }`}
              >
                {siteScore.delta >= 0 ? (
                  <TrendingUp className="h-4 w-4" aria-hidden />
                ) : (
                  <TrendingDown className="h-4 w-4" aria-hidden />
                )}
                {siteScore.delta >= 0 ? '+' : ''}
                {siteScore.delta} pts
              </span>
            )}
          </div>
          <SeoScoreBar score={siteScore.score} className="mt-4" />
          {siteScore.breakdown.length > 0 && (
            <dl className="mt-4 space-y-2">
              {siteScore.breakdown.map((b) => (
                <div key={b.category} className="flex items-center justify-between text-sm">
                  <dt className="text-muted-foreground capitalize">{b.category}</dt>
                  <dd className="text-foreground tabular-nums">
                    {b.score}/{100} <span className="text-muted-foreground">({b.weight}%)</span>
                  </dd>
                </div>
              ))}
            </dl>
          )}
        </SectionCard>

        <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:col-span-2">
          {metrics.length === 0 ? (
            <div className="sm:col-span-2">
              <SeoEmptyState
                title="No metrics yet"
                description="Run an audit to populate site metrics."
              />
            </div>
          ) : (
            metrics.map((m) => (
              <div key={m.label} className="border-border bg-card rounded-lg border p-4">
                <p className="text-muted-foreground text-sm">{m.label}</p>
                <p className="text-foreground mt-1 text-2xl font-medium tabular-nums">{m.value}</p>
                <p className="text-muted-foreground mt-1 flex items-center gap-1.5 text-sm">
                  <TrendIcon trend={m.trend} />
                  {m.helper}
                </p>
              </div>
            ))
          )}
        </div>
      </div>

      {/* Issues found + quick wins */}
      <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
        <SectionCard title="Issues Found">
          <ul className="space-y-3">
            <li className="flex items-center justify-between">
              <span className="text-foreground flex items-center gap-2 text-sm">
                <AlertOctagon className="text-destructive h-4 w-4" aria-hidden /> Critical
              </span>
              <span className="text-foreground font-medium tabular-nums">
                {issuesSummary.critical}
              </span>
            </li>
            <li className="flex items-center justify-between">
              <span className="text-foreground flex items-center gap-2 text-sm">
                <AlertTriangle className="text-warning h-4 w-4" aria-hidden /> Warnings
              </span>
              <span className="text-foreground font-medium tabular-nums">
                {issuesSummary.warning}
              </span>
            </li>
            <li className="flex items-center justify-between">
              <span className="text-foreground flex items-center gap-2 text-sm">
                <Info className="text-muted-foreground h-4 w-4" aria-hidden /> Info
              </span>
              <span className="text-foreground font-medium tabular-nums">{issuesSummary.info}</span>
            </li>
          </ul>
        </SectionCard>

        <SectionCard title="Quick Wins" description="High-impact fixes ranked by priority">
          {quickWins.length === 0 ? (
            <SeoEmptyState
              icon={<Zap size={24} />}
              title="No quick wins"
              description="Great — no high-impact issues are waiting."
            />
          ) : (
            <ul className="divide-border divide-y">
              {quickWins.map((w) => {
                const tone = impactTone(w.impact)
                const toneCls =
                  tone === 'poor'
                    ? 'bg-destructive/10 text-destructive'
                    : tone === 'fair'
                      ? 'bg-warning/10 text-warning'
                      : 'bg-success/10 text-success'
                return (
                  <li key={w.id} className="flex items-start justify-between gap-3 py-3 first:pt-0">
                    <div className="min-w-0">
                      <p className="text-foreground text-sm font-medium">{w.title}</p>
                      <p className="text-muted-foreground mt-0.5 text-sm">{w.explanation}</p>
                    </div>
                    <div className="flex shrink-0 items-center gap-2">
                      <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${toneCls}`}>
                        {w.impact}
                      </span>
                      {w.issueId && onOpenIssue && (
                        <button
                          onClick={() => onOpenIssue(w.issueId as string)}
                          className="text-primary hover:bg-accent focus-visible:ring-ring inline-flex items-center gap-1 rounded-md px-2 py-1 text-sm focus-visible:ring-2 focus-visible:outline-none"
                        >
                          Fix <ArrowRight className="h-3.5 w-3.5" aria-hidden />
                        </button>
                      )}
                    </div>
                  </li>
                )
              })}
            </ul>
          )}
        </SectionCard>
      </div>

      {/* Search performance */}
      <SectionCard title="Search Performance" description="Top pages by impressions (last 28 days)">
        {!searchConsoleConnected ? (
          <SeoEmptyState
            icon={<BarChart3 size={24} />}
            title="Search Console not connected"
            description="Connect Google Search Console to see real impressions, clicks, CTR, and average position."
            action={
              onConnectSearchConsole ? (
                <button className={btnSecondary} onClick={onConnectSearchConsole}>
                  Connect Search Console
                </button>
              ) : undefined
            }
          />
        ) : searchPerformance.length === 0 ? (
          <SeoEmptyState title="No search performance data" />
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm" aria-label="Search performance">
              <thead>
                <tr className="text-muted-foreground border-border border-b text-left">
                  <th className="py-2 pr-4 font-medium">Page</th>
                  <th className="py-2 pr-4 text-right font-medium">Impressions</th>
                  <th className="py-2 pr-4 text-right font-medium">Clicks</th>
                  <th className="py-2 pr-4 text-right font-medium">CTR</th>
                  <th className="py-2 text-right font-medium">Avg. Position</th>
                </tr>
              </thead>
              <tbody className="divide-border divide-y">
                {searchPerformance.map((row) => (
                  <tr key={row.url}>
                    <td className="py-2 pr-4">
                      <span className="text-foreground block font-medium">{row.title}</span>
                      <span className="text-muted-foreground block truncate">{row.url}</span>
                    </td>
                    <td className="text-foreground py-2 pr-4 text-right tabular-nums">
                      {row.impressions.toLocaleString()}
                    </td>
                    <td className="text-foreground py-2 pr-4 text-right tabular-nums">
                      {row.clicks.toLocaleString()}
                    </td>
                    <td className="text-foreground py-2 pr-4 text-right tabular-nums">
                      {(row.ctr * 100).toFixed(1)}%
                    </td>
                    <td className="text-foreground py-2 text-right tabular-nums">
                      {row.averagePosition.toFixed(1)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </SectionCard>
    </div>
  )
}
