"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { useLocale, useTranslations } from "next-intl"
import {
  Building2, MapPin, Phone, Loader2,
  ArrowLeft, Save, AlertTriangle,
} from "lucide-react"

import { COUNTRIES } from "@/src/lib/constants/countries"
import {
  createTenant,
  updateTenant,
  type Tenant,
  type TenantStatus,
} from "@/src/lib/api/tenants"

// ── Palette ACX ────────────────────────────────────────────────────────────
const NAVY  = "#1a3578"
const NAVY2 = "#2655b0"
const TEAL  = "#4dba96"

// ── Types ──────────────────────────────────────────────────────────────────
export type FormState = {
  name: string
  status: TenantStatus
  plan: string
  country: string
  city: string
  address_line1: string
  address_line2: string
  postal_code: string
  phone: string
  email: string
  website: string
  timezone: string
  currency: string
}

export const defaultForm: FormState = {
  name: "",
  status: "active",
  plan: "",
  country: "TD",
  city: "",
  address_line1: "",
  address_line2: "",
  postal_code: "",
  phone: "",
  email: "",
  website: "",
  timezone: "Africa/Ndjamena",
  currency: "XAF",
}

function toNull(v: string) {
  return v.trim() === "" ? null : v.trim()
}

// ── Sous-composants ────────────────────────────────────────────────────────
const inputCls =
  "w-full rounded-xl border border-slate-200 bg-white px-3.5 py-2.5 text-sm text-slate-800 outline-none placeholder:text-slate-400 transition-all duration-150 hover:border-slate-300 focus:border-[#4dba96] focus:shadow-[0_0_0_3px_rgba(77,186,150,0.15)] disabled:cursor-not-allowed disabled:opacity-50"

function Field({
  label, required, span2 = false, children,
}: {
  label: string; required?: boolean; span2?: boolean; children: React.ReactNode
}) {
  return (
    <div className={span2 ? "md:col-span-2" : ""}>
      <label className="mb-1.5 block text-[11px] font-semibold uppercase tracking-widest text-slate-400">
        {label}{required && <span className="ml-0.5 text-red-400">*</span>}
      </label>
      {children}
    </div>
  )
}

function SectionTitle({ children }: { children: React.ReactNode }) {
  return (
    <div className="mb-4 flex items-center gap-3">
      <div className="h-px flex-1 bg-slate-100" />
      <span className="text-[10px] font-bold uppercase tracking-widest text-slate-400">{children}</span>
      <div className="h-px flex-1 bg-slate-100" />
    </div>
  )
}

// ── Composant principal ────────────────────────────────────────────────────
export function TenantForm({ existing }: { existing?: Tenant }) {
  const locale = useLocale()
  const router = useRouter()
  const t = useTranslations("tenants")

  const isEdit = !!existing

  const [form, setForm] = useState<FormState>(
    existing
      ? {
          name:         existing.name ?? "",
          status:       existing.status ?? "active",
          plan:         existing.plan ?? "",
          country:      existing.country ?? "TD",
          city:         existing.city ?? "",
          address_line1: existing.address_line1 ?? "",
          address_line2: existing.address_line2 ?? "",
          postal_code:  existing.postal_code ?? "",
          phone:        existing.phone ?? "",
          email:        existing.email ?? "",
          website:      existing.website ?? "",
          timezone:     existing.timezone ?? "Africa/Ndjamena",
          currency:     existing.currency ?? "XAF",
        }
      : defaultForm
  )

  const [saving, setSaving] = useState(false)
  const [error, setError]   = useState<string | null>(null)

  const set = (patch: Partial<FormState>) => setForm((s) => ({ ...s, ...patch }))

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault()
    setSaving(true)
    setError(null)
    try {
      const payload = {
        name:          form.name.trim(),
        status:        form.status,
        plan:          toNull(form.plan),
        country:       toNull(form.country),
        city:          toNull(form.city),
        address_line1: toNull(form.address_line1),
        address_line2: toNull(form.address_line2),
        postal_code:   toNull(form.postal_code),
        phone:         toNull(form.phone),
        email:         toNull(form.email),
        website:       toNull(form.website),
        timezone:      toNull(form.timezone),
        currency:      toNull(form.currency),
      }

      if (isEdit) await updateTenant(existing!.id, payload as any)
      else        await createTenant(payload as any)

      router.push(`/${locale}/admin/tenants`)
    } catch (e: any) {
      setError(e?.message ?? "Une erreur est survenue")
      setSaving(false)
    }
  }

  return (
    <form onSubmit={onSubmit} noValidate>

      {/* En-tête de page */}
      <div className="mb-8 flex items-start justify-between gap-4">
        <div>
          <button
            type="button"
            onClick={() => router.back()}
            className="mb-3 flex items-center gap-1.5 text-sm text-slate-400 transition hover:text-slate-700"
          >
            <ArrowLeft className="h-4 w-4" />
            Retour à la liste
          </button>
          <div className="flex items-center gap-3">
            <div
              className="flex h-11 w-11 items-center justify-center rounded-2xl shadow-sm"
              style={{ background: `linear-gradient(135deg, ${NAVY}15, ${TEAL}10)`, border: `1.5px solid ${NAVY}20` }}
            >
              <Building2 className="h-5 w-5" style={{ color: NAVY }} />
            </div>
            <div>
              <h1 className="text-2xl font-bold text-slate-900">
                {isEdit ? t("edit_title") : t("create_title")}
              </h1>
              <p className="text-sm text-slate-500">
                {isEdit ? `Modification — ${existing!.name}` : "Ajouter un nouveau tenant à la plateforme"}
              </p>
            </div>
          </div>
        </div>

        {/* Boutons d'action top */}
        <div className="flex shrink-0 items-center gap-2">
          <button
            type="button"
            onClick={() => router.back()}
            disabled={saving}
            className="rounded-xl border bg-white px-4 py-2.5 text-sm font-medium text-slate-600 shadow-sm transition hover:bg-slate-50 disabled:opacity-50"
          >
            {t("cancel")}
          </button>
          <button
            type="submit"
            disabled={saving}
            className="flex items-center gap-2 rounded-xl px-5 py-2.5 text-sm font-semibold text-white shadow-sm transition active:scale-95 disabled:opacity-70 hover:opacity-90"
            style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
          >
            {saving
              ? <Loader2 className="h-4 w-4 animate-spin" />
              : <Save className="h-4 w-4" />
            }
            {saving ? t("saving") : isEdit ? t("save") : t("create")}
          </button>
        </div>
      </div>

      {/* Erreur */}
      {error && (
        <div className="mb-6 flex items-start gap-3 rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">
          <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
          <span>{error}</span>
        </div>
      )}

      {/* Corps du formulaire */}
      <div className="space-y-8">

        {/* ── Identité ─────────────────────────────────────────────────── */}
        <div className="rounded-2xl border bg-white p-6 shadow-sm">
          <SectionTitle>Identité</SectionTitle>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <Field label={t("fields.name")} required>
              <input
                className={inputCls}
                value={form.name}
                onChange={(e) => set({ name: e.target.value })}
                required
                disabled={saving}
                placeholder="Ex : UBA-CHAD"
              />
            </Field>

            <Field label={t("fields.status")}>
              <select
                className={inputCls}
                value={form.status}
                onChange={(e) => set({ status: e.target.value as TenantStatus })}
                disabled={saving}
              >
                <option value="active">{t("status.active")}</option>
                <option value="suspended">{t("status.suspended")}</option>
              </select>
            </Field>

            <Field label={t("fields.plan")}>
              <select
                className={inputCls}
                value={form.plan}
                onChange={(e) => set({ plan: e.target.value })}
                disabled={saving}
              >
                <option value="">— Choisir un plan —</option>
                <option value="Starter">Starter</option>
                <option value="Business">Business</option>
                <option value="Enterprise">Enterprise</option>
              </select>
            </Field>

            <Field label={t("fields.currency")}>
              <select
                className={inputCls}
                value={form.currency}
                onChange={(e) => set({ currency: e.target.value })}
                disabled={saving}
              >
                <option value="XAF">XAF — Franc CFA BEAC</option>
                <option value="XOF">XOF — Franc CFA BCEAO</option>
                <option value="USD">USD — Dollar américain</option>
                <option value="EUR">EUR — Euro</option>
                <option value="GBP">GBP — Livre sterling</option>
              </select>
            </Field>
          </div>
        </div>

        {/* ── Localisation ──────────────────────────────────────────────── */}
        <div className="rounded-2xl border bg-white p-6 shadow-sm">
          <SectionTitle>Localisation</SectionTitle>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <Field label={t("fields.country")}>
              <select
                className={inputCls}
                value={form.country}
                onChange={(e) => set({ country: e.target.value })}
                disabled={saving}
              >
                {COUNTRIES.map((c) => (
                  <option key={c.code} value={c.code}>
                    {locale === "fr" ? c.fr : c.en} ({c.code})
                  </option>
                ))}
              </select>
            </Field>

            <Field label={t("fields.city")}>
              <input
                className={inputCls}
                value={form.city}
                onChange={(e) => set({ city: e.target.value })}
                disabled={saving}
                placeholder="N'Djaména"
              />
            </Field>

            <Field label={t("fields.address1")} span2>
              <input
                className={inputCls}
                value={form.address_line1}
                onChange={(e) => set({ address_line1: e.target.value })}
                disabled={saving}
                placeholder="Adresse ligne 1"
              />
            </Field>

            <Field label={t("fields.address2")} span2>
              <input
                className={inputCls}
                value={form.address_line2}
                onChange={(e) => set({ address_line2: e.target.value })}
                disabled={saving}
                placeholder="Complément d'adresse (optionnel)"
              />
            </Field>

            <Field label={t("fields.postal_code")}>
              <input
                className={inputCls}
                value={form.postal_code}
                onChange={(e) => set({ postal_code: e.target.value })}
                disabled={saving}
                placeholder="Code postal"
              />
            </Field>

            <Field label="Fuseau horaire">
              <input
                className={inputCls}
                value={form.timezone}
                onChange={(e) => set({ timezone: e.target.value })}
                disabled={saving}
                placeholder="Africa/Ndjamena"
              />
            </Field>
          </div>
        </div>

        {/* ── Contact ──────────────────────────────────────────────────── */}
        <div className="rounded-2xl border bg-white p-6 shadow-sm">
          <SectionTitle>Contact</SectionTitle>
          <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
            <Field label={t("fields.phone")}>
              <input
                className={inputCls}
                value={form.phone}
                onChange={(e) => set({ phone: e.target.value })}
                disabled={saving}
                placeholder="+235 00 00 00 00"
              />
            </Field>

            <Field label={t("fields.email")}>
              <input
                type="email"
                className={inputCls}
                value={form.email}
                onChange={(e) => set({ email: e.target.value })}
                disabled={saving}
                placeholder="contact@tenant.com"
              />
            </Field>

            <Field label={t("fields.website")} span2>
              <input
                className={inputCls}
                value={form.website}
                onChange={(e) => set({ website: e.target.value })}
                disabled={saving}
                placeholder="https://www.tenant.com"
              />
            </Field>
          </div>
        </div>

        {/* Boutons bas */}
        <div className="flex justify-end gap-3 pb-4">
          <button
            type="button"
            onClick={() => router.back()}
            disabled={saving}
            className="rounded-xl border bg-white px-5 py-2.5 text-sm font-medium text-slate-600 shadow-sm transition hover:bg-slate-50 disabled:opacity-50"
          >
            {t("cancel")}
          </button>
          <button
            type="submit"
            disabled={saving}
            className="flex items-center gap-2 rounded-xl px-6 py-2.5 text-sm font-semibold text-white shadow-sm transition active:scale-95 disabled:opacity-70 hover:opacity-90"
            style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}
          >
            {saving
              ? <Loader2 className="h-4 w-4 animate-spin" />
              : <Save className="h-4 w-4" />
            }
            {saving ? t("saving") : isEdit ? t("save") : t("create")}
          </button>
        </div>

      </div>
    </form>
  )
}
