'use client'

import { useEffect } from "react"
import { PageHeader } from "@/components/ui/page-header"
import { KpiCard } from "@/components/ui/kpi-card"
import { SectionCard } from "@/components/ui/section-card"
import { StatusBadge, type StatusTone } from "@/components/ui/status-badge"
import { Settings, Cog, Link2, Globe, ShieldCheck } from "lucide-react"
import { formatDateTime } from "@/lib/format"
import { useSettings } from "@/hooks/useSettings"
import i18n from "@/lib/i18n";

const intMap: Record<string, { label: string; tone: StatusTone }> = {
  connected: { label: i18n.t('app.admin.settings.page.text_1'), tone: "success" },
  degraded: { label: i18n.t('app.admin.settings.page.text_2'), tone: "warning" },
  disconnected: { label: i18n.t('app.admin.settings.page.text_3'), tone: "danger" },
}

export default function SettingsPage() {
  const { items: settings, fetchItems, isLoading } = useSettings()

  useEffect(() => {
    fetchItems()
  }, [fetchItems])

  const integrations = settings.filter((s) => !s.is_feature_flag)
  const flags = settings.filter((s) => s.is_feature_flag)

  const connected = integrations.filter((i) => i.enabled).length
  const enabledFlags = flags.filter((f) => f.enabled).length

  if (isLoading) {
    return (
      <div className="flex h-[50vh] items-center justify-center">
        <div className="flex flex-col items-center gap-4">
          <div className="h-8 w-8 animate-spin rounded-full border-4 border-gold-500 border-t-transparent" />
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      <PageHeader
        title={i18n.t('app.admin.settings.page.text_4')}
        description={i18n.t('app.admin.settings.page.text_5')}
        breadcrumbs={[{ label: i18n.t('app.admin.settings.page.text_6'), href: "#" }, { label: i18n.t('app.admin.settings.page.text_7') }]}
      />

      <div className="grid grid-cols-2 gap-4 md:grid-cols-4">
        <KpiCard label={i18n.t('app.admin.settings.page.text_8')} value={`${connected}/${integrations.length}`} icon={Link2} tone="gold" accent />
        <KpiCard label={i18n.t('app.admin.settings.page.text_9')} value={`${enabledFlags}/${flags.length}`} icon={Cog} tone="success" />
        <KpiCard label={i18n.t('app.admin.settings.page.text_10')} value="Production" icon={Globe} tone="info" />
        <KpiCard label={i18n.t('app.admin.settings.page.text_11')} value="A+" icon={ShieldCheck} tone="success" />
      </div>

      <div className="grid gap-6 lg:grid-cols-2">
        <SectionCard title={i18n.t('app.admin.settings.page.text_12')} icon={<Link2 className="h-4 w-4 text-gold-600" />}>
          {integrations.length === 0 ? (
            <p className="text-[13px] text-muted-foreground text-center py-8">{i18n.t('app.admin.settings.page.text_25')}</p>
          ) : (
            <div className="space-y-3">
              {integrations.map((i) => (
                <div key={i.id} className="flex items-center justify-between rounded-lg border border-border bg-card p-3">
                  <div>
                    <p className="text-[13px] font-semibold">{i.description}</p>
                    <p className="text-[11.5px] text-muted-foreground">{i.value || i.key}</p>
                    <p className="text-[11px] text-muted-foreground mt-0.5">
                      {i18n.t('app.admin.settings.page.text_26')}{i.created_at ? formatDateTime(i.created_at) : "—"}
                    </p>
                  </div>
                  <StatusBadge tone={i.enabled ? "success" : "danger"} size="sm">{i.enabled ? i18n.t('app.admin.settings.page.text_13') : i18n.t('app.admin.settings.page.text_14')}</StatusBadge>
                </div>
              ))}
            </div>
          )}
        </SectionCard>

        <SectionCard title={i18n.t('app.admin.settings.page.text_15')} icon={<Settings className="h-4 w-4 text-gold-600" />}>
          {flags.length === 0 ? (
            <p className="text-[13px] text-muted-foreground text-center py-8">{i18n.t('app.admin.settings.page.text_27')}</p>
          ) : (
            <div className="space-y-3">
              {flags.map((f) => (
                <div key={f.id} className="flex items-center justify-between gap-3 rounded-lg border border-border bg-card p-3">
                  <div className="min-w-0">
                    <p className="font-mono text-[12.5px] font-semibold">{f.key}</p>
                    <p className="text-[11.5px] text-muted-foreground truncate">{f.description ?? "—"}</p>
                    <p className="text-[10.5px] text-muted-foreground mt-0.5 uppercase tracking-wider">{f.environment ?? "production"}</p>
                  </div>
                  <span
                    className={`inline-flex h-6 w-11 shrink-0 items-center rounded-full transition ${
                      f.enabled ? "bg-emerald-500 justify-end" : "bg-muted justify-start"
                    }`}
                  >
                    <span className="h-5 w-5 rounded-full bg-white mx-0.5 shadow-sm" />
                  </span>
                </div>
              ))}
            </div>
          )}
        </SectionCard>
      </div>

      <SectionCard title={i18n.t('app.admin.settings.page.text_16')} icon={<Globe className="h-4 w-4 text-gold-600" />}>
        <div className="grid gap-4 md:grid-cols-3">
          <PrefCard title={i18n.t('app.admin.settings.page.text_17')} value={i18n.t('app.admin.settings.page.text_18')} note={i18n.t('app.admin.settings.page.text_19')} />
          <PrefCard title={i18n.t('app.admin.settings.page.text_20')} value={i18n.t('app.admin.settings.page.text_21')} note={i18n.t('app.admin.settings.page.text_22')} />
          <PrefCard title={i18n.t('app.admin.settings.page.text_23')} value="Asia/Riyadh (UTC+3)" note={i18n.t('app.admin.settings.page.text_24')} />
        </div>
      </SectionCard>
    </div>
  )
}

function PrefCard({ title, value, note }: { title: string; value: string; note: string }) {
  return (
    <div className="rounded-lg border border-border bg-gradient-to-br from-gold-50/40 to-card p-3.5">
      <p className="text-[11.5px] uppercase tracking-wider text-muted-foreground">{title}</p>
      <p className="mt-1 text-[13.5px] font-semibold">{value}</p>
      <p className="mt-1 text-[11.5px] text-muted-foreground">{note}</p>
    </div>
  )
}