'use client'

import { useState } from 'react'
import { Info } from 'lucide-react'
import { ConfirmDangerousSettingDialog, SettingsCard, SettingsToggleRow } from './components.js'
import type { GeneralSettingsForm, SiteIndexStatus } from './useGeneralSettings.js'

interface SeoRobotsDefaultsCardProps {
  form: GeneralSettingsForm
  setField: <K extends keyof GeneralSettingsForm>(key: K, value: GeneralSettingsForm[K]) => void
  isProduction: boolean
  indexStatus: SiteIndexStatus | null
  canEdit: boolean
  onNavigate?: (path: string) => void
}

interface PendingChange {
  field: keyof GeneralSettingsForm
  value: boolean
  title: string
  description: string
  confirmLabel: string
}

export function SeoRobotsDefaultsCard({
  form,
  setField,
  isProduction,
  indexStatus,
  canEdit,
  onNavigate,
}: SeoRobotsDefaultsCardProps) {
  const [pending, setPending] = useState<PendingChange | null>(null)

  // Some toggles can take the whole production site out of search results, so
  // they route through a confirmation step before being applied.
  function requestToggle(field: keyof GeneralSettingsForm, value: boolean) {
    if (field === 'defaultNoIndex' && value && isProduction) {
      setPending({
        field,
        value,
        title: 'Block this production site from search engines?',
        description:
          'This may prevent search engines from indexing your production site. Pages will be served with a noindex directive unless they explicitly opt in.',
        confirmLabel: 'Enable No Index',
      })
      return
    }
    if (field === 'noIndexNonProduction' && !value) {
      setPending({
        field,
        value,
        title: 'Allow non-production environments to be indexed?',
        description:
          'Preview and staging environments may become indexable if publicly accessible. Search engines could index unfinished content.',
        confirmLabel: 'Turn Off',
      })
      return
    }
    setField(field, value)
  }

  const effectiveProd = form.defaultNoIndex ? 'Blocked' : 'Indexable'
  const sitemapCheck = indexStatus?.checks.find((c) => c.key === 'sitemap')
  const sitemapStatus = sitemapCheck ? (sitemapCheck.value === 'Yes' ? 'Enabled' : 'Disabled') : '—'

  return (
    <SettingsCard
      title="SEO & Robots Defaults"
      description="Set the site-wide default for search engine indexing. Individual pages can inherit or override these rules in their SEO panel. These share the same configuration as the SEO section."
    >
      <div className="space-y-4">
        <SettingsToggleRow
          label="Default No Index"
          description="Ask search engines not to index pages unless a page explicitly allows indexing."
          checked={form.defaultNoIndex}
          disabled={!canEdit}
          onChange={(v) => requestToggle('defaultNoIndex', v)}
        />
        <SettingsToggleRow
          label="Default No Follow"
          description="Ask search engines not to follow page links unless a page explicitly allows following."
          checked={form.defaultNoFollow}
          disabled={!canEdit}
          onChange={(v) => requestToggle('defaultNoFollow', v)}
        />
        <SettingsToggleRow
          label="Noindex Non-Production Environments"
          description="Force noindex when the deployed environment is not production."
          checked={form.noIndexNonProduction}
          disabled={!canEdit}
          onChange={(v) => requestToggle('noIndexNonProduction', v)}
        />
        {isProduction && (
          <p className="text-muted-foreground flex items-start gap-2 text-sm">
            <Info size={16} className="mt-0.5 shrink-0" aria-hidden="true" />
            This deployment is running in the production environment, so this setting does not
            change pages served here — it forces noindex only on preview, staging, and development
            deployments. To block search engines from this site, use Default No Index.
          </p>
        )}
      </div>

      <div className="border-border mt-4 space-y-2 border-t pt-4">
        <SummaryRow
          label="Effective production indexing"
          value={effectiveProd}
          danger={form.defaultNoIndex}
        />
        <SummaryRow
          label="Effective current environment"
          value={indexStatus?.label ?? '—'}
          danger={indexStatus?.severity === 'danger'}
        />
        <SummaryRow label="Sitemap status" value={sitemapStatus} />
        {onNavigate && (
          <button
            type="button"
            onClick={() => onNavigate('/seo?tab=technical')}
            className="text-brand mt-1 text-sm hover:underline"
          >
            Manage advanced robots.txt &amp; sitemap in SEO →
          </button>
        )}
      </div>

      <ConfirmDangerousSettingDialog
        open={pending !== null}
        title={pending?.title ?? ''}
        description={pending?.description ?? ''}
        confirmLabel={pending?.confirmLabel}
        onConfirm={() => {
          if (pending) setField(pending.field, pending.value)
          setPending(null)
        }}
        onCancel={() => setPending(null)}
      />
    </SettingsCard>
  )
}

function SummaryRow({ label, value, danger }: { label: string; value: string; danger?: boolean }) {
  return (
    <div className="flex items-center justify-between gap-2 text-sm">
      <span className="text-muted-foreground">{label}</span>
      <span className={danger ? 'text-destructive font-medium' : 'text-foreground font-medium'}>
        {value}
      </span>
    </div>
  )
}
