"use client"

import { useEffect, useState } from "react"
import { useParams, useRouter } from "next/navigation"
import { useLocale } from "next-intl"
import {
  ArrowLeft, UserPlus, Loader2, AlertTriangle, Save,
  Eye, EyeOff, Users, UserCheck, Shield,
} from "lucide-react"

import { getTenant, type Tenant } from "@/src/lib/api/tenants"
import { listRoles, createMembership, listMembershipsByTenant, type Role } from "@/src/lib/api/memberships"
import { listUsers, createUser, type User } from "@/src/lib/api/users"

const NAVY  = "#1a3578"
const NAVY2 = "#2655b0"
const TEAL  = "#4dba96"

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 hover:border-slate-300 focus:border-[#4dba96] focus:shadow-[0_0_0_3px_rgba(77,186,150,0.15)] disabled:opacity-50"

function Field({ label, required, hint, children }: { label: string; required?: boolean; hint?: string; children: React.ReactNode }) {
  return (
    <div>
      <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}
      {hint && <p className="mt-1 text-[11px] text-slate-400">{hint}</p>}
    </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>
  )
}

function displayName(u: User) {
  return [u.first_name, u.last_name].filter(Boolean).join(" ") || u.username
}

// Checkboxes multi-rôles
function RolesSelector({
  roles, selected, onChange, disabled,
}: {
  roles: Role[]; selected: number[]; onChange: (ids: number[]) => void; disabled?: boolean
}) {
  function toggle(id: number) {
    onChange(selected.includes(id) ? selected.filter((x) => x !== id) : [...selected, id])
  }
  if (roles.length === 0) return <p className="text-sm text-slate-400">Aucun rôle disponible.</p>
  return (
    <div className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
      {roles.map((r) => {
        const active = selected.includes(r.id)
        return (
          <button
            key={r.id}
            type="button"
            disabled={disabled}
            onClick={() => toggle(r.id)}
            className="flex items-center gap-3 rounded-xl border px-4 py-3 text-left text-sm font-medium transition active:scale-95 disabled:opacity-50"
            style={active
              ? { borderColor: NAVY, background: `${NAVY}0d`, color: NAVY }
              : { borderColor: "#e2e8f0", background: "#fff", color: "#475569" }}
          >
            <div
              className="flex h-5 w-5 shrink-0 items-center justify-center rounded-md border-2 transition"
              style={active
                ? { borderColor: NAVY, backgroundColor: NAVY }
                : { borderColor: "#cbd5e1", backgroundColor: "#fff" }}
            >
              {active && (
                <svg className="h-3 w-3 text-white" fill="none" viewBox="0 0 12 12">
                  <path d="M2 6l3 3 5-5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              )}
            </div>
            <span className="font-semibold">{r.label}</span>
            {active && <Shield className="ml-auto h-3.5 w-3.5 shrink-0" style={{ color: TEAL }} />}
          </button>
        )
      })}
    </div>
  )
}

export default function AddTenantUserPage() {
  const { id } = useParams<{ id: string }>()
  const tenantId = Number(id)
  const locale   = useLocale()
  const router   = useRouter()

  const [tenant,    setTenant]    = useState<Tenant | null>(null)
  const [roles,     setRoles]     = useState<Role[]>([])
  const [allUsers,  setAllUsers]  = useState<User[]>([])
  const [memberIds, setMemberIds] = useState<Set<number>>(new Set())
  const [loading,   setLoading]   = useState(true)

  const [mode,   setMode]   = useState<"existing" | "new">("existing")
  const [saving, setSaving] = useState(false)
  const [error,  setError]  = useState<string | null>(null)

  // ── Mode : utilisateur existant ─────────────────────────────────────────
  const [pickUser,    setPickUser]    = useState<number | "">("")
  const [pickRoles,   setPickRoles]   = useState<number[]>([])
  const [pickIsOwner, setPickIsOwner] = useState(false)
  const [pickStatus,  setPickStatus]  = useState<"active" | "invited">("active")

  // ── Mode : nouveau compte ───────────────────────────────────────────────
  const [nFirst,    setNFirst]    = useState("")
  const [nLast,     setNLast]     = useState("")
  const [nUser,     setNUser]     = useState("")
  const [nEmail,    setNEmail]    = useState("")
  const [nPwd,      setNPwd]      = useState("")
  const [showPwd,   setShowPwd]   = useState(false)
  const [nRoles,    setNRoles]    = useState<number[]>([])
  const [nIsOwner,  setNIsOwner]  = useState(false)
  const [nStatus,   setNStatus]   = useState<"active" | "invited">("active")

  useEffect(() => {
    Promise.all([
      getTenant(tenantId),
      listRoles(),
      listUsers(),
      listMembershipsByTenant(tenantId),
    ]).then(([t, r, u, m]) => {
      setTenant(t)
      setRoles(r)
      setAllUsers(u)
      setMemberIds(new Set(m.map((x) => typeof x.user === "object" ? (x.user as any).id : x.user as number)))
    }).catch((e) => setError(e?.message ?? "Erreur de chargement"))
    .finally(() => setLoading(false))
  }, [tenantId])

  const available    = allUsers.filter((u) => !memberIds.has(u.id))
  const selectedUser = allUsers.find((u) => u.id === pickUser)

  async function onSubmitExisting(e: React.FormEvent) {
    e.preventDefault()
    if (!pickUser) return
    setSaving(true); setError(null)
    try {
      await createMembership({
        tenant:   tenantId,
        user:     Number(pickUser),
        roles:    pickRoles,
        status:   pickStatus,
        is_owner: pickIsOwner,
      })
      router.push(`/${locale}/admin/tenants/${tenantId}`)
    } catch (ex: any) { setError(ex?.message ?? "Erreur"); setSaving(false) }
  }

  async function onSubmitNew(e: React.FormEvent) {
    e.preventDefault()
    setSaving(true); setError(null)
    try {
      const u = await createUser({
        username:   nUser.trim(),
        email:      nEmail.trim(),
        first_name: nFirst.trim() || undefined,
        last_name:  nLast.trim()  || undefined,
        password:   nPwd,
        is_active:  true,
      })
      await createMembership({
        tenant:   tenantId,
        user:     u.id,
        roles:    nRoles,
        status:   nStatus,
        is_owner: nIsOwner,
      })
      router.push(`/${locale}/admin/tenants/${tenantId}`)
    } catch (ex: any) { setError(ex?.message ?? "Erreur"); setSaving(false) }
  }

  if (loading) return (
    <div className="flex items-center justify-center gap-2 py-24 text-sm text-slate-400">
      <Loader2 className="h-5 w-5 animate-spin" /> Chargement…
    </div>
  )

  // ── Bloc accès commun ────────────────────────────────────────────────────
  function AccessBlock({
    roles: roleList, selectedRoles, onChangeRoles, isOwner, onChangeOwner, status, onChangeStatus, disabled,
  }: {
    roles: Role[]; selectedRoles: number[]; onChangeRoles: (ids: number[]) => void;
    isOwner: boolean; onChangeOwner: (v: boolean) => void;
    status: "active" | "invited"; onChangeStatus: (v: "active" | "invited") => void;
    disabled?: boolean;
  }) {
    return (
      <div className="rounded-2xl border bg-white p-6 shadow-sm">
        <SectionTitle>Accès au tenant</SectionTitle>
        <div className="space-y-5">

          {/* Rôles */}
          <Field
            label="Rôles attribués"
            hint="Un utilisateur peut cumuler plusieurs rôles (ex: administrateur + agent)."
          >
            <div className="mt-2">
              <RolesSelector roles={roleList} selected={selectedRoles} onChange={onChangeRoles} disabled={disabled} />
              {selectedRoles.length > 0 && (
                <p className="mt-2 text-[11px] text-slate-500">
                  {selectedRoles.length} rôle{selectedRoles.length > 1 ? "s" : ""} :{" "}
                  <span className="font-semibold" style={{ color: NAVY }}>
                    {selectedRoles.map((rid) => roleList.find((r) => r.id === rid)?.label ?? rid).join(", ")}
                  </span>
                </p>
              )}
            </div>
          </Field>

          {/* Propriétaire */}
          <div className="flex items-center gap-3 rounded-xl border p-4"
            style={{ borderColor: isOwner ? `${NAVY}30` : "#e2e8f0", background: isOwner ? `${NAVY}06` : "#fff" }}>
            <input id="is_owner_block" type="checkbox" checked={isOwner}
              onChange={(e) => onChangeOwner(e.target.checked)} disabled={disabled}
              className="h-4 w-4 rounded accent-[#1a3578]" />
            <label htmlFor="is_owner_block" className="flex-1 cursor-pointer">
              <span className="text-sm font-semibold text-slate-800">Propriétaire du tenant</span>
              <p className="text-[11px] text-slate-500 mt-0.5">Accès complet, peut gérer tous les membres et paramètres.</p>
            </label>
            {isOwner && <Shield className="h-4 w-4 shrink-0" style={{ color: TEAL }} />}
          </div>

          {/* Statut */}
          <Field label="Statut initial">
            <div className="mt-1 flex gap-2">
              {([
                { value: "active",  label: "Actif",  color: "#059669", bg: "rgba(5,150,105,0.08)"  },
                { value: "invited", label: "Invité", color: NAVY2,     bg: `${NAVY2}0d`            },
              ] as const).map((s) => (
                <button key={s.value} type="button" disabled={disabled}
                  onClick={() => onChangeStatus(s.value)}
                  className="flex-1 rounded-xl border py-2.5 text-sm font-semibold transition active:scale-95 disabled:opacity-50"
                  style={status === s.value
                    ? { borderColor: s.color, background: s.bg, color: s.color }
                    : { borderColor: "#e2e8f0", background: "#fff", color: "#64748b" }}>
                  {s.label}
                </button>
              ))}
            </div>
          </Field>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">

      {/* Navigation */}
      <div>
        <button onClick={() => router.push(`/${locale}/admin/tenants/${tenantId}`)}
          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 — {tenant?.name}
        </button>
        <div className="flex items-center gap-3">
          <div className="flex h-11 w-11 items-center justify-center rounded-2xl ring-1"
            style={{ background: `${NAVY}10`, borderColor: `${NAVY}20` }}>
            <UserPlus className="h-5 w-5" style={{ color: NAVY }} />
          </div>
          <div>
            <h1 className="text-xl font-bold text-slate-900">Ajouter un utilisateur</h1>
            <p className="text-sm text-slate-500">Tenant : <span className="font-medium text-slate-700">{tenant?.name}</span></p>
          </div>
        </div>
      </div>

      {error && (
        <div className="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" />{error}
        </div>
      )}

      {/* Sélecteur de mode */}
      <div className="flex gap-3">
        {([
          { id: "existing", label: "Rattacher un utilisateur existant", sub: "Choisir parmi les comptes déjà créés", icon: Users },
          { id: "new",      label: "Créer un nouveau compte",           sub: "Créer un compte utilisateur et l'attacher", icon: UserPlus },
        ] as const).map(({ id: mid, label, sub, icon: Icon }) => (
          <button key={mid} onClick={() => setMode(mid)} type="button"
            className="flex flex-1 items-start gap-3 rounded-2xl border p-4 text-left transition"
            style={mode === mid ? { borderColor: NAVY, background: `${NAVY}08` } : { borderColor: "#e2e8f0", background: "#fff" }}>
            <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl"
              style={mode === mid ? { background: NAVY, color: "#fff" } : { background: "#f1f5f9", color: "#64748b" }}>
              <Icon className="h-4 w-4" />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-sm font-semibold" style={{ color: mode === mid ? NAVY : "#334155" }}>{label}</p>
              <p className="text-[11px] text-slate-400 mt-0.5">{sub}</p>
            </div>
            <div className="mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition"
              style={mode === mid ? { borderColor: NAVY, backgroundColor: NAVY } : { borderColor: "#cbd5e1" }}>
              {mode === mid && <div className="h-2 w-2 rounded-full bg-white" />}
            </div>
          </button>
        ))}
      </div>

      {/* ── Mode : utilisateur existant ──────────────────────────────────── */}
      {mode === "existing" && (
        <form onSubmit={onSubmitExisting} className="space-y-6">
          <div className="rounded-2xl border bg-white p-6 shadow-sm">
            <SectionTitle>Sélection de l'utilisateur</SectionTitle>
            {available.length === 0 ? (
              <div className="rounded-xl border border-dashed border-slate-200 p-6 text-center">
                <Users className="mx-auto mb-2 h-8 w-8 text-slate-300" />
                <p className="text-sm text-slate-500">Tous les utilisateurs sont déjà membres de ce tenant.</p>
              </div>
            ) : (
              <div className="space-y-4">
                <Field label="Utilisateur" required>
                  <select className={inputCls} value={pickUser} required disabled={saving}
                    onChange={(e) => setPickUser(e.target.value ? Number(e.target.value) : "")}>
                    <option value="">— Sélectionner un utilisateur —</option>
                    {available.map((u) => (
                      <option key={u.id} value={u.id}>
                        {displayName(u)} — {u.email ?? ""} (@{u.username})
                      </option>
                    ))}
                  </select>
                </Field>

                {selectedUser && (
                  <div className="flex items-center gap-3 rounded-xl border bg-slate-50 px-4 py-3">
                    <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl text-[11px] font-bold text-white"
                      style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
                      {displayName(selectedUser).slice(0, 2).toUpperCase()}
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className="font-semibold text-slate-800">{displayName(selectedUser)}</p>
                      <p className="text-[12px] text-slate-500">{selectedUser.email}</p>
                      <p className="font-mono text-[11px] text-slate-400">@{selectedUser.username}</p>
                    </div>
                    <UserCheck className="h-5 w-5 text-emerald-500 shrink-0" />
                  </div>
                )}
              </div>
            )}
          </div>

          <AccessBlock
            roles={roles}
            selectedRoles={pickRoles}
            onChangeRoles={setPickRoles}
            isOwner={pickIsOwner}
            onChangeOwner={setPickIsOwner}
            status={pickStatus}
            onChangeStatus={setPickStatus}
            disabled={saving}
          />

          <div className="flex justify-end gap-3">
            <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">
              Annuler
            </button>
            <button type="submit" disabled={saving || !pickUser}
              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-60"
              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 ? "Enregistrement…" : "Confirmer l'ajout"}
            </button>
          </div>
        </form>
      )}

      {/* ── Mode : nouveau compte ─────────────────────────────────────────── */}
      {mode === "new" && (
        <form onSubmit={onSubmitNew} className="space-y-6">
          <div className="rounded-2xl border bg-white p-6 shadow-sm">
            <SectionTitle>Informations personnelles</SectionTitle>
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
              <Field label="Prénom">
                <input className={inputCls} value={nFirst} onChange={(e) => setNFirst(e.target.value)} disabled={saving} placeholder="Alladoum" />
              </Field>
              <Field label="Nom">
                <input className={inputCls} value={nLast} onChange={(e) => setNLast(e.target.value)} disabled={saving} placeholder="Kone" />
              </Field>
              <Field label="Nom d'utilisateur" required>
                <input className={inputCls} value={nUser} onChange={(e) => setNUser(e.target.value)} required disabled={saving} placeholder="alladoum.kone" />
              </Field>
              <Field label="Email" required>
                <input type="email" className={inputCls} value={nEmail} onChange={(e) => setNEmail(e.target.value)} required disabled={saving} placeholder="jean@tenant.com" />
              </Field>
              <Field label="Mot de passe" required hint="Minimum 6 caractères">
                <div className="relative">
                  <input type={showPwd ? "text" : "password"} className={inputCls + " pr-12"}
                    value={nPwd} onChange={(e) => setNPwd(e.target.value)} required disabled={saving} placeholder="••••••••" />
                  <button type="button" tabIndex={-1} onClick={() => setShowPwd((v) => !v)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-600">
                    {showPwd ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
                  </button>
                </div>
              </Field>
            </div>
          </div>

          <AccessBlock
            roles={roles}
            selectedRoles={nRoles}
            onChangeRoles={setNRoles}
            isOwner={nIsOwner}
            onChangeOwner={setNIsOwner}
            status={nStatus}
            onChangeStatus={setNStatus}
            disabled={saving}
          />

          <div className="flex justify-end gap-3">
            <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">
              Annuler
            </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-60"
              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 ? "Création en cours…" : "Créer et rattacher"}
            </button>
          </div>
        </form>
      )}
    </div>
  )
}
