"use client"

import { useEffect, useState } from "react"
import { useTranslations } from "next-intl"
import { Globe, Shield } from "lucide-react"
import { api } from "@/src/lib/api/client"

const NAVY = "#1a3578"
const TEAL = "#4dba96"

const TIMEZONES = [
  "Africa/Abidjan", "Africa/Accra", "Africa/Douala", "Africa/Lagos",
  "Africa/Nairobi", "Africa/Dakar", "Africa/Bamako", "Africa/Libreville",
  "Europe/Paris", "Europe/London", "UTC",
]

const CURRENCIES = ["XAF", "XOF", "EUR", "USD", "GBP", "MAD", "TND", "NGN", "GHS", "KES"]

type PlatformCfg = {
  platform_name: string
  default_currency: string
  default_language: string
  timezone: string
  support_email: string
}

function SectionCard({ icon: Icon, title, children }: {
  icon: React.ElementType; title: string; children: React.ReactNode
}) {
  return (
    <div className="rounded-2xl border bg-card">
      <div className="flex items-center gap-3 px-6 py-4 border-b">
        <div className="h-9 w-9 rounded-xl flex items-center justify-center shrink-0" style={{ background: `${NAVY}12` }}>
          <Icon className="h-4 w-4" style={{ color: NAVY }} />
        </div>
        <p className="font-semibold text-sm">{title}</p>
      </div>
      <div className="p-6">{children}</div>
    </div>
  )
}

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="space-y-1.5">
      <label className="text-xs font-medium text-muted-foreground">{label}</label>
      {children}
    </div>
  )
}

// ─── Platform Section ─────────────────────────────────────────────────────────

function PlatformSection({ t }: { t: any }) {
  const [form, setForm] = useState<PlatformCfg | null>(null)
  const [saving, setSaving] = useState(false)
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null)

  useEffect(() => {
    api.request<PlatformCfg>("platform-settings/").then(setForm).catch(() => {})
  }, [])

  const set = (k: keyof PlatformCfg, v: string) => setForm((f) => f ? { ...f, [k]: v } : f)

  async function save() {
    if (!form || saving) return
    setSaving(true); setMsg(null)
    try {
      await api.request("platform-settings/", { method: "PUT", body: JSON.stringify(form) })
      setMsg({ ok: true, text: t("platform_saved") })
    } catch (e: any) {
      setMsg({ ok: false, text: e?.message ?? "Erreur" })
    } finally {
      setSaving(false)
    }
  }

  if (!form) return (
    <SectionCard icon={Globe} title={t("platform_title")}>
      <p className="text-sm text-muted-foreground">{t("loading")}</p>
    </SectionCard>
  )

  return (
    <SectionCard icon={Globe} title={t("platform_title")}>
      <div className="space-y-4">
        <div className="grid grid-cols-2 gap-4">
          <Field label={t("platform_name")}>
            <input value={form.platform_name} onChange={(e) => set("platform_name", e.target.value)}
              className="w-full rounded-xl border bg-muted/30 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary/30" />
          </Field>
          <Field label={t("platform_support_email")}>
            <input type="email" value={form.support_email} onChange={(e) => set("support_email", e.target.value)}
              placeholder="support@example.com"
              className="w-full rounded-xl border bg-muted/30 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary/30" />
          </Field>
          <Field label={t("platform_currency")}>
            <select value={form.default_currency} onChange={(e) => set("default_currency", e.target.value)}
              className="w-full rounded-xl border bg-muted/30 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary/30">
              {CURRENCIES.map((c) => <option key={c} value={c}>{c}</option>)}
            </select>
          </Field>
          <Field label={t("platform_language")}>
            <select value={form.default_language} onChange={(e) => set("default_language", e.target.value)}
              className="w-full rounded-xl border bg-muted/30 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary/30">
              <option value="fr">Français</option>
              <option value="en">English</option>
            </select>
          </Field>
          <Field label={t("platform_timezone")}>
            <select value={form.timezone} onChange={(e) => set("timezone", e.target.value)}
              className="w-full rounded-xl border bg-muted/30 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary/30 col-span-2">
              {TIMEZONES.map((tz) => <option key={tz} value={tz}>{tz}</option>)}
            </select>
          </Field>
        </div>

        <div className="flex items-center justify-between pt-2">
          {msg && <p className={`text-sm ${msg.ok ? "text-emerald-600" : "text-destructive"}`}>{msg.text}</p>}
          <div className="ml-auto">
            <button onClick={save} disabled={saving}
              className="rounded-xl px-4 py-2.5 text-sm font-medium text-white disabled:opacity-40"
              style={{ background: NAVY }}>
              {saving ? t("saving") : t("save")}
            </button>
          </div>
        </div>
      </div>
    </SectionCard>
  )
}

// ─── Security Section (read-only info) ───────────────────────────────────────

function SecuritySection({ t }: { t: any }) {
  const items = [
    { label: t("sec_jwt_access"),  value: "15 minutes" },
    { label: t("sec_jwt_refresh"), value: "7 jours" },
    { label: t("sec_pwd_min"),     value: "6 caractères" },
    { label: t("sec_sessions"),    value: t("sec_sessions_hint") },
  ]

  return (
    <SectionCard icon={Shield} title={t("security_title")}>
      <div className="grid grid-cols-2 gap-3">
        {items.map((item) => (
          <div key={item.label} className="rounded-xl bg-muted/40 px-4 py-3">
            <p className="text-xs text-muted-foreground mb-0.5">{item.label}</p>
            <p className="text-sm font-medium">{item.value}</p>
          </div>
        ))}
      </div>
      <p className="text-xs text-muted-foreground mt-4">
        {t("sec_manage_hint")}
      </p>
    </SectionCard>
  )
}

// ─── Page ─────────────────────────────────────────────────────────────────────

export default function AdminSettingsPage() {
  const t = useTranslations("admin.settings")

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-xl font-semibold">{t("title")}</h1>
        <p className="text-sm text-muted-foreground">{t("subtitle")}</p>
      </div>
      <PlatformSection t={t} />
      <SecuritySection t={t} />
    </div>
  )
}
