"use client"

import { useEffect, useState } from "react"
import { useTranslations } from "next-intl"
import {
  Mail, MessageSquare, Key, RefreshCw, Check, X,
  Send, Eye, EyeOff, Plus, Trash2, Copy, CheckCheck,
} from "lucide-react"
import { api } from "@/src/lib/api/client"
import { listTenants, type Tenant } from "@/src/lib/api/tenants"

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

// ─── Types ──────────────────────────────────────────────────────────────────

type EmailStatus = {
  host: string; port: number; user: string
  use_tls: boolean; from: string; is_configured: boolean
}

type SmsConfig = {
  provider: string; sender_id: string
  api_key: string; api_secret: string; is_active: boolean
}

type ApiKey = {
  id: number; tenant_id: number; tenant_name: string
  label: string; key_prefix: string; is_active: boolean
  created_by: string; last_used_at: string | null; created_at: string
  raw_key?: string
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

function Badge({ ok, label }: { ok: boolean; label: string }) {
  return (
    <span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-medium ${
      ok ? "bg-emerald-100 text-emerald-700" : "bg-muted text-muted-foreground"
    }`}>
      {ok ? <Check className="h-3 w-3" /> : <X className="h-3 w-3" />}
      {label}
    </span>
  )
}

function SectionCard({ icon: Icon, title, badge, children }: {
  icon: React.ElementType; title: string; badge?: React.ReactNode; 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 flex-1">{title}</p>
        {badge}
      </div>
      <div className="p-6">{children}</div>
    </div>
  )
}

// ─── Email Section ────────────────────────────────────────────────────────────

function EmailSection({ t }: { t: any }) {
  const [status, setStatus]   = useState<EmailStatus | null>(null)
  const [testTo, setTestTo]   = useState("")
  const [sending, setSending] = useState(false)
  const [msg, setMsg]         = useState<{ ok: boolean; text: string } | null>(null)

  useEffect(() => {
    api.request<EmailStatus>("integration/email/").then(setStatus).catch(() => {})
  }, [])

  async function sendTest() {
    if (!testTo.trim() || sending) return
    setSending(true); setMsg(null)
    try {
      const r = await api.request<{ detail: string }>("integration/email/", {
        method: "POST", body: JSON.stringify({ to: testTo }),
      })
      setMsg({ ok: true, text: r.detail })
    } catch (e: any) {
      setMsg({ ok: false, text: e?.message ?? "Erreur" })
    } finally {
      setSending(false)
    }
  }

  return (
    <SectionCard icon={Mail} title={t("email_title")}
      badge={status ? <Badge ok={status.is_configured} label={status.is_configured ? t("configured") : t("not_configured")} /> : null}>
      {!status ? (
        <p className="text-sm text-muted-foreground">{t("loading")}</p>
      ) : (
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-3 text-sm">
            <div className="rounded-xl bg-muted/40 px-4 py-3">
              <p className="text-xs text-muted-foreground mb-0.5">{t("email_host")}</p>
              <p className="font-mono font-medium">{status.host || "—"}</p>
            </div>
            <div className="rounded-xl bg-muted/40 px-4 py-3">
              <p className="text-xs text-muted-foreground mb-0.5">{t("email_port")}</p>
              <p className="font-mono font-medium">{status.port}</p>
            </div>
            <div className="rounded-xl bg-muted/40 px-4 py-3">
              <p className="text-xs text-muted-foreground mb-0.5">{t("email_user")}</p>
              <p className="font-mono font-medium truncate">{status.user || "—"}</p>
            </div>
            <div className="rounded-xl bg-muted/40 px-4 py-3">
              <p className="text-xs text-muted-foreground mb-0.5">{t("email_tls")}</p>
              <p className="font-medium">{status.use_tls ? "TLS activé" : "Non"}</p>
            </div>
          </div>

          <div className="flex gap-2 items-center pt-2">
            <input
              type="email"
              value={testTo}
              onChange={(e) => setTestTo(e.target.value)}
              placeholder={t("email_test_placeholder")}
              className="flex-1 rounded-xl border bg-muted/30 px-4 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary/30"
            />
            <button
              onClick={sendTest}
              disabled={sending || !testTo.trim()}
              className="flex items-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium text-white disabled:opacity-40 transition-all"
              style={{ background: NAVY }}
            >
              <Send className="h-3.5 w-3.5" />
              {sending ? t("sending") : t("email_test_btn")}
            </button>
          </div>
          {msg && (
            <p className={`text-sm ${msg.ok ? "text-emerald-600" : "text-destructive"}`}>{msg.text}</p>
          )}
        </div>
      )}
    </SectionCard>
  )
}

// ─── SMS Section ─────────────────────────────────────────────────────────────

const SMS_PROVIDERS = ["twilio", "orange", "mtn", "aws", "other"]

function SmsSection({ t }: { t: any }) {
  const [cfg, setCfg]     = useState<SmsConfig | null>(null)
  const [form, setForm]   = useState<SmsConfig | null>(null)
  const [saving, setSaving] = useState(false)
  const [showKey, setShowKey]   = useState(false)
  const [showSecret, setShowSecret] = useState(false)
  const [msg, setMsg]     = useState<{ ok: boolean; text: string } | null>(null)

  useEffect(() => {
    api.request<SmsConfig>("integration/sms/").then((c) => { setCfg(c); setForm(c) }).catch(() => {})
  }, [])

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

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

  return (
    <SectionCard icon={MessageSquare} title={t("sms_title")}
      badge={cfg ? <Badge ok={cfg.is_active} label={cfg.is_active ? t("active") : t("inactive")} /> : null}>
      {!form ? (
        <p className="text-sm text-muted-foreground">{t("loading")}</p>
      ) : (
        <div className="space-y-4">
          <div className="grid grid-cols-2 gap-3">
            <div className="space-y-1">
              <label className="text-xs font-medium text-muted-foreground">{t("sms_provider")}</label>
              <select
                value={form.provider}
                onChange={(e) => set("provider", 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"
              >
                {SMS_PROVIDERS.map((p) => (
                  <option key={p} value={p}>{t(`sms_provider_${p}`)}</option>
                ))}
              </select>
            </div>
            <div className="space-y-1">
              <label className="text-xs font-medium text-muted-foreground">{t("sms_sender_id")}</label>
              <input
                value={form.sender_id}
                onChange={(e) => set("sender_id", e.target.value)}
                placeholder="ACX"
                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"
              />
            </div>
            <div className="space-y-1">
              <label className="text-xs font-medium text-muted-foreground">{t("sms_api_key")}</label>
              <div className="relative">
                <input
                  type={showKey ? "text" : "password"}
                  value={form.api_key}
                  onChange={(e) => set("api_key", e.target.value)}
                  className="w-full rounded-xl border bg-muted/30 px-3 py-2.5 pr-10 text-sm outline-none focus:ring-2 focus:ring-primary/30"
                />
                <button onClick={() => setShowKey(!showKey)} className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground">
                  {showKey ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>
            <div className="space-y-1">
              <label className="text-xs font-medium text-muted-foreground">{t("sms_api_secret")}</label>
              <div className="relative">
                <input
                  type={showSecret ? "text" : "password"}
                  value={form.api_secret}
                  onChange={(e) => set("api_secret", e.target.value)}
                  className="w-full rounded-xl border bg-muted/30 px-3 py-2.5 pr-10 text-sm outline-none focus:ring-2 focus:ring-primary/30"
                />
                <button onClick={() => setShowSecret(!showSecret)} className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground">
                  {showSecret ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                </button>
              </div>
            </div>
          </div>

          <div className="flex items-center justify-between pt-2">
            <label className="flex items-center gap-2 cursor-pointer">
              <div
                onClick={() => set("is_active", !form.is_active)}
                className={`w-10 h-5 rounded-full transition-colors relative cursor-pointer ${form.is_active ? "bg-emerald-500" : "bg-muted"}`}
              >
                <div className={`absolute top-0.5 h-4 w-4 rounded-full bg-white shadow transition-all ${form.is_active ? "left-5" : "left-0.5"}`} />
              </div>
              <span className="text-sm">{t("sms_active")}</span>
            </label>
            <button
              onClick={save}
              disabled={saving}
              className="rounded-xl px-4 py-2 text-sm font-medium text-white disabled:opacity-40"
              style={{ background: TEAL }}
            >
              {saving ? t("saving") : t("save")}
            </button>
          </div>
          {msg && <p className={`text-sm ${msg.ok ? "text-emerald-600" : "text-destructive"}`}>{msg.text}</p>}
        </div>
      )}
    </SectionCard>
  )
}

// ─── API Keys Section ─────────────────────────────────────────────────────────

function ApiKeysSection({ t, tenants }: { t: any; tenants: Tenant[] }) {
  const [keys, setKeys]         = useState<ApiKey[]>([])
  const [loading, setLoading]   = useState(true)
  const [form, setForm]         = useState({ tenant_id: "", label: "" })
  const [creating, setCreating] = useState(false)
  const [newKey, setNewKey]     = useState<ApiKey | null>(null)
  const [copied, setCopied]     = useState(false)
  const [error, setError]       = useState<string | null>(null)

  async function loadKeys() {
    try {
      const data = await api.request<ApiKey[]>("integration/api-keys/")
      setKeys(data)
    } catch {}
    setLoading(false)
  }

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

  async function generate() {
    if (!form.tenant_id || !form.label.trim() || creating) return
    setCreating(true); setError(null)
    try {
      const k = await api.request<ApiKey>("integration/api-keys/", {
        method: "POST",
        body: JSON.stringify({ tenant_id: Number(form.tenant_id), label: form.label }),
      })
      setNewKey(k)
      setKeys((prev) => [k, ...prev])
      setForm({ tenant_id: "", label: "" })
    } catch (e: any) {
      setError(e?.message ?? "Erreur")
    } finally {
      setCreating(false)
    }
  }

  async function revoke(id: number) {
    try {
      await api.request(`integration/api-keys/${id}/`, { method: "DELETE" })
      setKeys((prev) => prev.map((k) => k.id === id ? { ...k, is_active: false } : k))
    } catch {}
  }

  function copy(raw: string) {
    navigator.clipboard.writeText(raw)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)
  }

  return (
    <SectionCard icon={Key} title={t("apikeys_title")} badge={<span className="text-xs text-muted-foreground">{keys.filter(k => k.is_active).length} {t("apikeys_active_count")}</span>}>
      {/* New Key Form */}
      <div className="flex gap-2 mb-4">
        <select
          value={form.tenant_id}
          onChange={(e) => setForm((f) => ({ ...f, tenant_id: e.target.value }))}
          className="rounded-xl border bg-muted/30 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary/30 flex-1"
        >
          <option value="">{t("apikeys_select_tenant")}</option>
          {tenants.map((tn) => (
            <option key={tn.id} value={tn.id}>{tn.name}</option>
          ))}
        </select>
        <input
          value={form.label}
          onChange={(e) => setForm((f) => ({ ...f, label: e.target.value }))}
          placeholder={t("apikeys_label_placeholder")}
          className="rounded-xl border bg-muted/30 px-3 py-2.5 text-sm outline-none focus:ring-2 focus:ring-primary/30 flex-1"
        />
        <button
          onClick={generate}
          disabled={creating || !form.tenant_id || !form.label.trim()}
          className="flex items-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium text-white disabled:opacity-40 shrink-0"
          style={{ background: NAVY }}
        >
          <Plus className="h-3.5 w-3.5" />
          {t("apikeys_generate")}
        </button>
      </div>

      {/* New key display */}
      {newKey?.raw_key && (
        <div className="mb-4 rounded-xl border-2 border-emerald-200 bg-emerald-50 p-4 space-y-2">
          <p className="text-sm font-semibold text-emerald-700">{t("apikeys_new_warning")}</p>
          <div className="flex items-center gap-2 rounded-lg bg-white border px-3 py-2">
            <code className="flex-1 text-xs font-mono break-all">{newKey.raw_key}</code>
            <button onClick={() => copy(newKey.raw_key!)} className="shrink-0 text-muted-foreground hover:text-foreground">
              {copied ? <CheckCheck className="h-4 w-4 text-emerald-600" /> : <Copy className="h-4 w-4" />}
            </button>
          </div>
          <button onClick={() => setNewKey(null)} className="text-xs text-emerald-600 hover:underline">{t("apikeys_dismiss")}</button>
        </div>
      )}

      {error && <p className="text-sm text-destructive mb-3">{error}</p>}

      {/* Table */}
      {loading ? (
        <p className="text-sm text-muted-foreground">{t("loading")}</p>
      ) : keys.length === 0 ? (
        <p className="text-sm text-muted-foreground text-center py-6">{t("apikeys_empty")}</p>
      ) : (
        <div className="rounded-xl border overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-muted/40">
              <tr>
                <th className="text-left px-4 py-2.5 text-xs font-medium text-muted-foreground">{t("apikeys_col_tenant")}</th>
                <th className="text-left px-4 py-2.5 text-xs font-medium text-muted-foreground">{t("apikeys_col_label")}</th>
                <th className="text-left px-4 py-2.5 text-xs font-medium text-muted-foreground">{t("apikeys_col_prefix")}</th>
                <th className="text-left px-4 py-2.5 text-xs font-medium text-muted-foreground">{t("apikeys_col_status")}</th>
                <th className="text-left px-4 py-2.5 text-xs font-medium text-muted-foreground">{t("apikeys_col_created")}</th>
                <th className="px-4 py-2.5" />
              </tr>
            </thead>
            <tbody className="divide-y">
              {keys.map((k) => (
                <tr key={k.id} className={`hover:bg-muted/20 transition-colors ${!k.is_active ? "opacity-50" : ""}`}>
                  <td className="px-4 py-3 font-medium">{k.tenant_name}</td>
                  <td className="px-4 py-3 text-muted-foreground">{k.label}</td>
                  <td className="px-4 py-3"><code className="text-xs bg-muted px-1.5 py-0.5 rounded">{k.key_prefix}…</code></td>
                  <td className="px-4 py-3">
                    <Badge ok={k.is_active} label={k.is_active ? t("active") : t("revoked")} />
                  </td>
                  <td className="px-4 py-3 text-xs text-muted-foreground">
                    {new Date(k.created_at).toLocaleDateString("fr-FR")}
                  </td>
                  <td className="px-4 py-3">
                    {k.is_active && (
                      <button onClick={() => revoke(k.id)} className="text-destructive/60 hover:text-destructive transition-colors" title={t("apikeys_revoke")}>
                        <Trash2 className="h-4 w-4" />
                      </button>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </SectionCard>
  )
}

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

export default function AdminIntegrationsPage() {
  const t = useTranslations("admin.integrations")
  const [tenants, setTenants] = useState<Tenant[]>([])

  useEffect(() => {
    listTenants().then(setTenants).catch(() => {})
  }, [])

  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>

      <EmailSection t={t} />
      <SmsSection t={t} />
      <ApiKeysSection t={t} tenants={tenants} />
    </div>
  )
}
