"use client"

import { useEffect, useRef, useState } from "react"
import { useTranslations } from "next-intl"
import { X, Eye, EyeOff } from "lucide-react"
import { api } from "@/src/lib/api/client"
import { useAuth } from "@/src/features/auth/auth-context"

type Props = {
  accentColor?: string
  secondaryColor?: string
}

export function ProfileDropdown({ accentColor = "#1a3578", secondaryColor = "#4dba96" }: Props) {
  const t = useTranslations("profile_dropdown")
  const { me, refreshMe } = useAuth()

  const [open, setOpen] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  const [form, setForm] = useState({ first_name: "", last_name: "", email: "", username: "" })
  const [pwd, setPwd] = useState({ new_password: "", confirm_password: "" })
  const [showPwd, setShowPwd] = useState(false)
  const [saving, setSaving] = useState(false)
  const [savingPwd, setSavingPwd] = useState(false)
  const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null)
  const [msgPwd, setMsgPwd] = useState<{ ok: boolean; text: string } | null>(null)
  const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({})

  useEffect(() => {
    if (me) setForm({
      first_name: me.first_name || "",
      last_name:  me.last_name  || "",
      email:      me.email      || "",
      username:   me.username   || "",
    })
  }, [me])

  useEffect(() => {
    if (!open) return
    function handler(e: MouseEvent) {
      if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false)
    }
    document.addEventListener("mousedown", handler)
    return () => document.removeEventListener("mousedown", handler)
  }, [open])

  const firstName   = me?.first_name ?? ""
  const lastName    = me?.last_name  ?? ""
  const username    = me?.username   ?? "—"
  const displayName = [firstName, lastName].filter(Boolean).join(" ") || username
  const initials    = (firstName[0] ?? username[0] ?? "?").toUpperCase()

  const set = (k: string, v: string) => {
    setForm(f => ({ ...f, [k]: v }))
    setFieldErrors(e => ({ ...e, [k]: "" }))
  }

  async function saveProfile() {
    if (saving) return
    setSaving(true); setMsg(null); setFieldErrors({})
    try {
      await api.request("auth/me/", { method: "PATCH", body: JSON.stringify(form) })
      setMsg({ ok: true, text: t("profile_saved") })
      await refreshMe()
    } catch (e: any) {
      const field = e?.field as string | undefined
      if (field) setFieldErrors({ [field]: e?.message ?? "Erreur" })
      else setMsg({ ok: false, text: e?.message ?? "Erreur" })
    } finally {
      setSaving(false)
    }
  }

  async function changePassword() {
    if (savingPwd) return
    if (pwd.new_password !== pwd.confirm_password) {
      setMsgPwd({ ok: false, text: t("pwd_mismatch") }); return
    }
    setSavingPwd(true); setMsgPwd(null)
    try {
      await api.request("users/change-password/", {
        method: "POST",
        body: JSON.stringify({ new_password: pwd.new_password, confirm_password: pwd.confirm_password }),
      })
      setMsgPwd({ ok: true, text: t("pwd_saved") })
      setPwd({ new_password: "", confirm_password: "" })
    } catch (e: any) {
      setMsgPwd({ ok: false, text: e?.message ?? "Erreur" })
    } finally {
      setSavingPwd(false)
    }
  }

  return (
    <div className="relative" ref={ref}>
      {/* ── Trigger (avatar chip) ─────────────────────────────────────── */}
      <button
        onClick={() => setOpen(o => !o)}
        title={t("click_to_edit")}
        className="hidden sm:flex items-center gap-2.5 rounded-xl px-3 py-1.5 transition-all"
        style={{
          background: `${accentColor}08`,
          border: `1px solid ${accentColor}${open ? "30" : "12"}`,
        }}
      >
        <div
          className="h-7 w-7 rounded-lg flex items-center justify-center text-xs font-bold text-white shrink-0"
          style={{ background: `linear-gradient(135deg, ${accentColor} 0%, ${accentColor}cc 100%)` }}
        >
          {initials}
        </div>
        <div className="flex flex-col items-start min-w-0">
          <span className="text-sm font-medium text-slate-700 max-w-[120px] truncate leading-tight">{displayName}</span>
          <span className="text-[10px] text-slate-400 leading-tight">{t("click_to_edit")}</span>
        </div>
      </button>

      {/* ── Floating panel ───────────────────────────────────────────── */}
      {open && (
        <div
          className="absolute right-0 top-full mt-2 z-50 w-80 rounded-2xl border bg-card overflow-hidden"
          style={{ boxShadow: "0 8px 32px rgba(0,0,0,0.12)" }}
        >
          {/* Header */}
          <div className="flex items-center justify-between px-4 py-3 border-b">
            <p className="text-sm font-semibold">{t("title")}</p>
            <button
              onClick={() => setOpen(false)}
              className="text-muted-foreground hover:text-foreground transition-colors"
            >
              <X className="h-4 w-4" />
            </button>
          </div>

          <div className="p-4 space-y-4 max-h-[70vh] overflow-y-auto">
            {/* Profile fields */}
            <div className="grid grid-cols-2 gap-3">
              {[
                { k: "first_name", label: t("first_name") },
                { k: "last_name",  label: t("last_name") },
                { k: "email",      label: t("email") },
                { k: "username",   label: t("username") },
              ].map(({ k, label }) => (
                <div key={k} className="space-y-1">
                  <label className="text-[11px] font-medium text-muted-foreground">{label}</label>
                  <input
                    type={k === "email" ? "email" : "text"}
                    value={(form as any)[k]}
                    onChange={e => set(k, e.target.value)}
                    className="w-full rounded-lg border bg-muted/30 px-2.5 py-2 text-xs outline-none focus:ring-2 focus:ring-primary/30"
                  />
                  {fieldErrors[k] && (
                    <p className="text-[10px] text-destructive mt-0.5">{fieldErrors[k]}</p>
                  )}
                </div>
              ))}
            </div>

            <div className="flex items-center justify-between">
              {msg && (
                <p className={`text-xs ${msg.ok ? "text-emerald-600" : "text-destructive"}`}>{msg.text}</p>
              )}
              <button
                onClick={saveProfile}
                disabled={saving}
                className="ml-auto rounded-lg px-3 py-1.5 text-xs font-medium text-white disabled:opacity-40"
                style={{ background: accentColor }}
              >
                {saving ? t("saving") : t("save")}
              </button>
            </div>

            {/* Password change */}
            <div className="border-t pt-4 space-y-3">
              <p className="text-xs font-semibold">{t("pwd_title")}</p>
              <div className="grid grid-cols-2 gap-3">
                <div className="space-y-1">
                  <label className="text-[11px] font-medium text-muted-foreground">{t("pwd_new")}</label>
                  <div className="relative">
                    <input
                      type={showPwd ? "text" : "password"}
                      value={pwd.new_password}
                      onChange={e => setPwd(p => ({ ...p, new_password: e.target.value }))}
                      className="w-full rounded-lg border bg-muted/30 px-2.5 py-2 pr-8 text-xs outline-none focus:ring-2 focus:ring-primary/30"
                    />
                    <button
                      onClick={() => setShowPwd(!showPwd)}
                      className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground"
                    >
                      {showPwd ? <EyeOff className="h-3 w-3" /> : <Eye className="h-3 w-3" />}
                    </button>
                  </div>
                </div>
                <div className="space-y-1">
                  <label className="text-[11px] font-medium text-muted-foreground">{t("pwd_confirm")}</label>
                  <input
                    type="password"
                    value={pwd.confirm_password}
                    onChange={e => setPwd(p => ({ ...p, confirm_password: e.target.value }))}
                    className="w-full rounded-lg border bg-muted/30 px-2.5 py-2 text-xs outline-none focus:ring-2 focus:ring-primary/30"
                  />
                </div>
              </div>
              <div className="flex items-center justify-between">
                {msgPwd && (
                  <p className={`text-xs ${msgPwd.ok ? "text-emerald-600" : "text-destructive"}`}>{msgPwd.text}</p>
                )}
                <button
                  onClick={changePassword}
                  disabled={savingPwd || !pwd.new_password}
                  className="ml-auto rounded-lg px-3 py-1.5 text-xs font-medium text-white disabled:opacity-40"
                  style={{ background: secondaryColor }}
                >
                  {savingPwd ? t("saving") : t("pwd_change_btn")}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
