'use client'

/**
 * SEO Operations Center — five-tab workflow surface (Overview / Content /
 * Technical / Redirects / Audit). Tab + deep-link state is driven by the
 * `?tab=` query string so audits, issues, redirects, and content editors are
 * all linkable. All data flows through `lib/seo-service.ts`.
 */
import * as Tabs from '@radix-ui/react-tabs'
import {
  LayoutDashboard,
  FileText,
  Settings2,
  ArrowRightLeft,
  ClipboardCheck,
  RefreshCw,
  Bot,
  Link2,
} from 'lucide-react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { parseRouteQuery } from '../router/index.js'
import { ErrorBoundary } from '../components/ErrorBoundary.js'
import { fetchSeoOverview, runSeoAudit } from '../lib/seo-service.js'
import { fetchPlanInfo, type PlanInfo } from '../lib/plan.js'
import { ScorePill, btnPrimary, btnSecondary } from '../components/seo/primitives.js'
import { SeoCopilotDrawer } from '../components/seo/SeoCopilotDrawer.js'
import { useSeoResource } from './seo/useSeoResource.js'
import { OverviewTab } from './seo/OverviewTab.js'
import { ContentTab } from './seo/ContentTab.js'
import { TechnicalTab } from './seo/TechnicalTab.js'
import { RedirectsTab } from './seo/RedirectsTab.js'
import { AuditTab } from './seo/AuditTab.js'
import { LinksTab } from './seo/LinksTab.js'

export interface SEOProps {
  onNavigate?: (path: string) => void
  initialTab?: string
}

const TABS = [
  { id: 'overview', label: 'Overview', icon: LayoutDashboard },
  { id: 'content', label: 'Content SEO', icon: FileText },
  { id: 'links', label: 'Links', icon: Link2 },
  { id: 'technical', label: 'Technical', icon: Settings2 },
  { id: 'redirects', label: 'Redirects', icon: ArrowRightLeft },
  { id: 'audit', label: 'Audit', icon: ClipboardCheck },
] as const

type TabId = (typeof TABS)[number]['id']

function normalizeTab(tab: string | undefined): TabId {
  const valid = TABS.map((t) => t.id) as string[]
  return (valid.includes(tab ?? '') ? tab : 'overview') as TabId
}

interface UrlState {
  tab: string | null
  entityType: string | null
  entityId: string | null
  issueId: string | null
}

/** Read tab + deep-link query params from the current URL. */
function readUrlState(): UrlState {
  if (typeof window === 'undefined') {
    return { tab: null, entityType: null, entityId: null, issueId: null }
  }
  const params = parseRouteQuery(window.location.search)
  return {
    tab: params.get('tab'),
    entityType: params.get('entityType'),
    entityId: params.get('entityId'),
    issueId: params.get('issueId'),
  }
}

export function SEO({ onNavigate, initialTab = 'overview' }: SEOProps) {
  const initialUrl = readUrlState()
  const [activeTab, setActiveTab] = useState<TabId>(normalizeTab(initialUrl.tab ?? initialTab))
  const [refetchKey, setRefetchKey] = useState(0)
  const [auditing, setAuditing] = useState(false)
  const [copilotOpen, setCopilotOpen] = useState(false)
  const [deepLink, setDeepLink] = useState<UrlState>(initialUrl)
  const [planInfo, setPlanInfo] = useState<PlanInfo | null>(null)

  useEffect(() => {
    void fetchPlanInfo().then(setPlanInfo)
  }, [])

  // Overview resource is owned here so the header score pill and the Overview
  // tab share a single request; `refetchKey` re-runs it after an audit.
  const overviewResource = useSeoResource(fetchSeoOverview, [refetchKey])

  // Keep tab + deep links in sync with browser back/forward navigation.
  useEffect(() => {
    function sync() {
      const url = readUrlState()
      setActiveTab(normalizeTab(url.tab ?? initialTab))
      setDeepLink(url)
    }
    window.addEventListener('popstate', sync)
    return () => window.removeEventListener('popstate', sync)
  }, [initialTab])

  useEffect(() => {
    const url = readUrlState()
    setActiveTab(normalizeTab(url.tab ?? initialTab))
    setDeepLink(url)
  }, [initialTab])

  const changeTab = useCallback(
    (tab: string) => {
      const next = normalizeTab(tab)
      setActiveTab(next)
      setDeepLink({ tab: next, entityType: null, entityId: null, issueId: null })
      onNavigate?.(`/seo?tab=${next}`)
    },
    [onNavigate],
  )

  const handleRunAudit = useCallback(async () => {
    setAuditing(true)
    const res = await runSeoAudit('full')
    setAuditing(false)
    if (res.error) {
      toast.error(res.error)
      return
    }
    toast.success('Audit complete.')
    setRefetchKey((k) => k + 1)
  }, [])

  const score = overviewResource.data?.siteScore.score

  const badgeCounts = useMemo(() => {
    const summary = overviewResource.data?.issuesSummary
    return { audit: summary ? summary.critical + summary.warning : 0 }
  }, [overviewResource.data])

  return (
    <div className="space-y-6 p-6">
      <header className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-foreground">SEO Operations Center</h1>
          <p className="text-muted-foreground mt-1 text-sm">
            Monitor, fix, and automate SEO across your content, redirects, and technical setup.
          </p>
        </div>
        <div className="flex items-center gap-3">
          {typeof score === 'number' && (
            <span className="text-muted-foreground flex items-center gap-2 text-sm">
              Site score <ScorePill score={score} />
            </span>
          )}
          <button className={btnSecondary} onClick={() => setCopilotOpen(true)}>
            <Bot className="h-4 w-4" aria-hidden />
            AI Copilot
          </button>
          <button className={btnPrimary} onClick={handleRunAudit} disabled={auditing}>
            <RefreshCw className={`h-4 w-4 ${auditing ? 'animate-spin' : ''}`} aria-hidden />
            {auditing ? 'Running audit…' : 'Run audit'}
          </button>
        </div>
      </header>

      <SeoCopilotDrawer open={copilotOpen} onOpenChange={setCopilotOpen} />

      <Tabs.Root value={activeTab} onValueChange={changeTab}>
        <Tabs.List
          className="border-border flex gap-1 overflow-x-auto border-b"
          aria-label="SEO sections"
        >
          {TABS.map((t) => {
            const Icon = t.icon
            const badge = t.id === 'audit' ? badgeCounts.audit : 0
            return (
              <Tabs.Trigger
                key={t.id}
                value={t.id}
                className="text-muted-foreground hover:text-foreground data-[state=active]:text-foreground data-[state=active]:border-primary focus-visible:ring-ring -mb-px flex items-center gap-2 border-b-2 border-transparent px-3 py-2.5 text-sm font-medium transition-colors focus-visible:ring-2 focus-visible:outline-none"
              >
                <Icon className="h-4 w-4" aria-hidden />
                {t.label}
                {badge > 0 && (
                  <span className="bg-destructive/10 text-destructive ml-1 rounded-full px-1.5 py-0.5 text-xs font-medium tabular-nums">
                    {badge}
                  </span>
                )}
              </Tabs.Trigger>
            )
          })}
        </Tabs.List>

        <div className="pt-6">
          <ErrorBoundary>
            <Tabs.Content value="overview" tabIndex={-1}>
              {activeTab === 'overview' && (
                <OverviewTab
                  resource={overviewResource}
                  onOpenIssue={(issueId) => onNavigate?.(`/seo?tab=audit&issueId=${issueId}`)}
                  onConnectSearchConsole={() =>
                    toast.info(
                      'Google Search Console integration is coming soon. Demo performance data is available in local development.',
                    )
                  }
                />
              )}
            </Tabs.Content>
            <Tabs.Content value="content" tabIndex={-1}>
              {activeTab === 'content' && (
                <ContentTab
                  initialEntityType={deepLink.entityType}
                  initialEntityId={deepLink.entityId}
                />
              )}
            </Tabs.Content>
            <Tabs.Content value="links" tabIndex={-1}>
              {activeTab === 'links' && <LinksTab onNavigate={onNavigate} />}
            </Tabs.Content>
            <Tabs.Content value="technical" tabIndex={-1}>
              {activeTab === 'technical' && <TechnicalTab />}
            </Tabs.Content>
            <Tabs.Content value="redirects" tabIndex={-1}>
              {activeTab === 'redirects' && <RedirectsTab />}
            </Tabs.Content>
            <Tabs.Content value="audit" tabIndex={-1}>
              {activeTab === 'audit' && (
                <AuditTab
                  refetchKey={refetchKey}
                  initialIssueId={deepLink.issueId}
                  onNavigate={onNavigate}
                  planInfo={planInfo}
                />
              )}
            </Tabs.Content>
          </ErrorBoundary>
        </div>
      </Tabs.Root>
    </div>
  )
}
