"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  User, EnvelopeSimple, Lock, FloppyDisk, ListChecks,
} from "@phosphor-icons/react";
import type { CustomerPayload } from "@/lib/customerAuth";
import { useLanguage } from "@/lib/i18n/context";

export default function ProfileClient({ customer }: { customer: CustomerPayload }) {
  const { t } = useLanguage();
  const router = useRouter();

  const [form, setForm] = useState({
    name:            customer.name,
    email:           customer.email,
    currentPassword: "",
    newPassword:     "",
    confirmPassword: "",
  });
  const [success, setSuccess] = useState("");
  const [error,   setError]   = useState("");
  const [loading, setLoading] = useState(false);

  const submitProfile = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setSuccess("");

    if (form.newPassword && form.newPassword !== form.confirmPassword) {
      setError(t.profil.errMismatch);
      return;
    }
    if (form.newPassword && form.newPassword.length < 6) {
      setError(t.profil.errTooShort);
      return;
    }

    setLoading(true);
    try {
      const res  = await fetch("/api/customer/update", {
        method:  "PATCH",
        headers: { "Content-Type": "application/json" },
        body:    JSON.stringify({
          name:            form.name.trim(),
          email:           form.email.trim(),
          currentPassword: form.currentPassword || undefined,
          newPassword:     form.newPassword     || undefined,
        }),
      });
      const data = await res.json();
      if (!res.ok) { setError(data.error); return; }
      setSuccess(t.profil.successMsg);
      setForm(f => ({ ...f, currentPassword: "", newPassword: "", confirmPassword: "" }));
      router.refresh();
    } finally {
      setLoading(false);
    }
  };

  const inputClass = "w-full bg-brand-sand-light border border-brand-dark/10 rounded-xl px-4 py-3 text-brand-dark text-sm placeholder-brand-dark/25 focus:outline-none focus:border-brand-yellow focus:bg-white transition-colors";

  return (
    <main className="min-h-screen bg-brand-sand-light pt-28 pb-16 px-4 sm:px-6">
      <div className="max-w-4xl mx-auto">
        <div className="grid grid-cols-1 lg:grid-cols-[220px_1fr] gap-6">

          {/* ── Sidebar ── */}
          <aside className="space-y-4">

            {/* User card */}
            <div className="bg-white rounded-3xl p-5 border border-brand-dark/8 shadow-sm text-center">
              <div className="w-14 h-14 rounded-2xl bg-brand-yellow flex items-center justify-center mx-auto mb-3">
                <User size={28} weight="bold" className="text-brand-dark" />
              </div>
              <p className="text-brand-dark font-bold text-sm leading-tight" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                {customer.name}
              </p>
              <p className="text-brand-dark/40 text-[11px] mt-0.5 truncate">{customer.email}</p>
            </div>

            {/* Quick links */}
            <div className="bg-white rounded-3xl p-2 border border-brand-dark/8 shadow-sm flex flex-col gap-1">
              <Link
                href="/suivi-commandes"
                className="flex items-center gap-3 px-4 py-3 rounded-2xl text-xs font-bold tracking-wide text-brand-dark/45 hover:bg-brand-dark/5 hover:text-brand-dark transition-colors"
              >
                <ListChecks size={14} weight="bold" /> {t.profil.orderTracking}
              </Link>
            </div>
          </aside>

          {/* ── Profile form ── */}
          <form onSubmit={submitProfile} className="space-y-5">

            <div className="bg-white rounded-3xl p-7 border border-brand-dark/8 shadow-sm">
              <h2 className="text-base font-bold text-brand-dark mb-5" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                {t.profil.personalInfo}
              </h2>
              <div className="space-y-4">
                <Field label={t.profil.fullName} icon={<User size={13} weight="bold" />}>
                  <input type="text" required value={form.name} placeholder={t.profil.fullNamePlaceholder}
                    onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
                    className={inputClass}
                  />
                </Field>
                <Field label={t.profil.email} icon={<EnvelopeSimple size={13} weight="bold" />}>
                  <input type="email" required value={form.email} placeholder="votre@email.com"
                    onChange={e => setForm(f => ({ ...f, email: e.target.value }))}
                    className={inputClass}
                  />
                </Field>
              </div>
            </div>

            <div className="bg-white rounded-3xl p-7 border border-brand-dark/8 shadow-sm">
              <h2 className="text-base font-bold text-brand-dark mb-1" style={{ fontFamily: "var(--font-space, sans-serif)" }}>
                {t.profil.password}
              </h2>
              <p className="text-brand-dark/40 text-xs mb-5">{t.profil.passwordHint}</p>
              <div className="space-y-4">
                <Field label={t.profil.currentPassword} icon={<Lock size={13} weight="bold" />}>
                  <input type="password" value={form.currentPassword} placeholder="••••••••"
                    autoComplete="new-password"
                    onChange={e => setForm(f => ({ ...f, currentPassword: e.target.value }))}
                    className={inputClass}
                  />
                </Field>
                <Field label={t.profil.newPassword} icon={<Lock size={13} weight="bold" />}>
                  <input type="password" value={form.newPassword} placeholder="••••••••"
                    onChange={e => setForm(f => ({ ...f, newPassword: e.target.value }))}
                    className={inputClass}
                  />
                </Field>
                {form.newPassword && (
                  <Field label={t.profil.confirmPassword} icon={<Lock size={13} weight="bold" />}>
                    <input type="password" value={form.confirmPassword} placeholder="••••••••"
                      onChange={e => setForm(f => ({ ...f, confirmPassword: e.target.value }))}
                      className={inputClass}
                    />
                  </Field>
                )}
              </div>
            </div>

            {error   && <p className="text-red-500 text-sm bg-red-50 border border-red-200 rounded-2xl px-5 py-4">{error}</p>}
            {success && <p className="text-green-600 text-sm bg-green-50 border border-green-200 rounded-2xl px-5 py-4">{success}</p>}

            <button
              type="submit"
              disabled={loading}
              className="w-full flex items-center justify-center gap-2 bg-brand-dark text-brand-yellow font-bold py-4 rounded-2xl text-sm tracking-wide hover:bg-brand-yellow hover:text-brand-dark disabled:opacity-50 transition-all duration-300"
            >
              <FloppyDisk size={15} weight="bold" />
              {loading ? t.profil.saving : t.profil.save}
            </button>
          </form>

        </div>
      </div>
    </main>
  );
}

function Field({ label, icon, children }: { label: string; icon: React.ReactNode; children: React.ReactNode }) {
  return (
    <div>
      <label className="flex items-center gap-1.5 text-brand-dark/45 text-[10px] font-bold tracking-[0.18em] uppercase mb-2">
        {icon} {label}
      </label>
      {children}
    </div>
  );
}
