'use client'

import {
  CheckCircle2,
  XCircle,
  AlertTriangle,
  HelpCircle,
  ExternalLink,
  Search,
} from 'lucide-react'
import type { ReactNode } from 'react'
import { SettingsCard } from './components.js'
import type { SiteIndexStatus } from './useGeneralSettings.js'

interface SiteIndexStatusCardProps {
  status: SiteIndexStatus | null
  loading: boolean
  /** Resolve an action href relative to the admin (e.g. /seo?tab=audit). */
  onNavigate?: (path: string) => void
  /** Trigger the SEO audit flow when an action declares `action: run_seo_audit`. */
  onRunAudit?: () => void
}

const SEVERITY_STYLES: Record<SiteIndexStatus['severity'], { pill: string; icon: ReactNode }> = {
  success: {
    pill: 'bg-success/15 text-success border-success/30',
    icon: <CheckCircle2 size={14} aria-hidden="true" />,
  },
  warning: {
    pill: 'bg-warning/15 text-warning border-warning/30',
    icon: <AlertTriangle size={14} aria-hidden="true" />,
  },
  danger: {
    pill: 'bg-destructive/10 text-destructive border-destructive/30',
    icon: <XCircle size={14} aria-hidden="true" />,
  },
  neutral: {
    pill: 'bg-muted text-muted-foreground border-border',
    icon: <HelpCircle size={14} aria-hidden="true" />,
  },
}

const CHECK_ICON: Record<string, ReactNode> = {
  pass: <CheckCircle2 size={14} className="text-success" aria-hidden="true" />,
  warning: <AlertTriangle size={14} className="text-warning" aria-hidden="true" />,
  fail: <XCircle size={14} className="text-destructive" aria-hidden="true" />,
  unknown: <HelpCircle size={14} className="text-muted-foreground" aria-hidden="true" />,
}

const CHECK_SR: Record<string, string> = {
  pass: 'OK',
  warning: 'Warning',
  fail: 'Problem',
  unknown: 'Unknown',
}

export function SiteIndexStatusCard({
  status,
  loading,
  onNavigate,
  onRunAudit,
}: SiteIndexStatusCardProps) {
  return (
    <SettingsCard
      title="Site Index Status"
      description="Current effective crawl and indexing state."
      actions={
        status ? (
          <span
            className={`inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium ${SEVERITY_STYLES[status.severity].pill}`}
          >
            {SEVERITY_STYLES[status.severity].icon}
            <span className="sr-only">Status: </span>
            {status.label}
          </span>
        ) : undefined
      }
    >
      {loading && !status ? (
        <div className="space-y-2" aria-hidden="true">
          <div className="bg-muted h-4 w-2/3 animate-pulse rounded" />
          <div className="bg-muted h-20 w-full animate-pulse rounded" />
        </div>
      ) : !status ? (
        <p className="text-muted-foreground text-sm">Index status is unavailable.</p>
      ) : (
        <>
          <p className="text-muted-foreground mb-3 text-sm">{status.description}</p>

          <dl className="border-border grid grid-cols-1 gap-x-6 gap-y-2 rounded-md border p-3 sm:grid-cols-2">
            {status.checks.map((check) => (
              <div key={check.key} className="flex items-center justify-between gap-2 text-sm">
                <dt className="text-muted-foreground">{check.label}</dt>
                <dd className="text-foreground flex items-center gap-1.5 font-medium">
                  <span className="sr-only">{CHECK_SR[check.status]}: </span>
                  {CHECK_ICON[check.status]}
                  {check.value}
                </dd>
              </div>
            ))}
          </dl>

          {status.actions.length > 0 && (
            <div className="mt-3 flex flex-wrap gap-2">
              {status.actions.map((action) => (
                <SiteIndexAction
                  key={action.label}
                  label={action.label}
                  href={action.href}
                  action={action.action}
                  onNavigate={onNavigate}
                  onRunAudit={onRunAudit}
                />
              ))}
            </div>
          )}
        </>
      )}
    </SettingsCard>
  )
}

function SiteIndexAction({
  label,
  href,
  action,
  onNavigate,
  onRunAudit,
}: {
  label: string
  href?: string
  action?: string
  onNavigate?: (path: string) => void
  onRunAudit?: () => void
}) {
  const className =
    'border-border text-foreground hover:bg-accent inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-sm transition-colors'

  // The audit action stays in-app; robots/sitemap are real public URLs.
  const isAudit = action === 'run_seo_audit'
  const isAdminRoute = href?.startsWith('/seo')
  const icon = isAudit ? (
    <Search size={14} aria-hidden="true" />
  ) : (
    <ExternalLink size={14} aria-hidden="true" />
  )

  if (isAudit && onRunAudit) {
    return (
      <button type="button" onClick={onRunAudit} className={className}>
        {icon}
        {label}
      </button>
    )
  }

  if (isAdminRoute && onNavigate) {
    return (
      <button type="button" onClick={() => onNavigate(href!)} className={className}>
        {icon}
        {label}
      </button>
    )
  }

  return (
    <a href={href} target="_blank" rel="noopener noreferrer" className={className}>
      {icon}
      {label}
    </a>
  )
}
