// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
"use client";

import { useState } from "react";

export type ProfileInitial = {
  name: string;
  bio: string;
  city: string;
  phone: string;
  website: string;
  job_title: string;
  company: string;
  birth_date: string;
  socials: Record<string, string>;
  isPublic: boolean;
  kaId: string;
};

const SOCIALS: { key: string; label: string; placeholder: string }[] = [
  { key: "instagram", label: "Instagram", placeholder: "@pseudo ou URL" },
  { key: "facebook", label: "Facebook", placeholder: "profil ou URL" },
  { key: "x", label: "X (Twitter)", placeholder: "@pseudo ou URL" },
  { key: "linkedin", label: "LinkedIn", placeholder: "profil ou URL" },
  { key: "tiktok", label: "TikTok", placeholder: "@pseudo ou URL" },
  { key: "youtube", label: "YouTube", placeholder: "chaîne ou URL" },
];

export default function ProfileForm({ initial }: { initial: ProfileInitial }) {
  const [form, setForm] = useState(initial);
  const [saving, setSaving] = useState(false);
  const [saved, setSaved] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isPublic, setIsPublic] = useState(initial.isPublic);
  const [copied, setCopied] = useState(false);

  const publicUrl = `https://www.groupe-ka.com/u/${initial.kaId}`;

  async function save() {
    setSaving(true);
    setError(null);
    const res = await fetch("/api/profile", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(form),
    });
    const data = await res.json().catch(() => ({}));
    setSaving(false);
    if (!res.ok) {
      setError(data.error ?? "Enregistrement impossible — réessayez.");
      return;
    }
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  }

  async function togglePublic(enabled: boolean) {
    await fetch("/api/profile/public", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ enabled }),
    });
    setIsPublic(enabled);
  }

  const field =
    (key: keyof ProfileInitial, max: number) =>
    (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>
      setForm({ ...form, [key]: e.target.value.slice(0, max) });

  return (
    <div className="space-y-5">
      <div className="grid gap-4 sm:grid-cols-2">
        <label className="block">
          <span className="klabel">Nom affiché</span>
          <input className="field mt-[6px]" value={form.name} onChange={field("name", 80)} placeholder="Prénom Nom" />
        </label>
        <label className="block">
          <span className="klabel">Ville</span>
          <input className="field mt-[6px]" value={form.city} onChange={field("city", 60)} placeholder="Québec, Montréal…" />
        </label>
      </div>

      <label className="block">
        <span className="klabel">Bio ({280 - form.bio.length} caractères restants)</span>
        <textarea
          className="field mt-[6px] resize-y"
          rows={3}
          value={form.bio}
          onChange={field("bio", 280)}
          placeholder="Présentez-vous en quelques mots…"
        />
      </label>

      <div className="grid gap-4 sm:grid-cols-2">
        <label className="block">
          <span className="klabel">Emploi / titre</span>
          <input className="field mt-[6px]" value={form.job_title} onChange={field("job_title", 80)} placeholder="Gestionnaire, courtier, développeur…" />
        </label>
        <label className="block">
          <span className="klabel">Entreprise</span>
          <input className="field mt-[6px]" value={form.company} onChange={field("company", 80)} placeholder="Nom de l'entreprise" />
        </label>
        <label className="block">
          <span className="klabel">Date de naissance</span>
          <input className="field mt-[6px]" type="date" value={form.birth_date} onChange={field("birth_date", 10)} />
        </label>
        <label className="block">
          <span className="klabel">Téléphone</span>
          <input className="field mt-[6px]" value={form.phone} onChange={field("phone", 40)} placeholder="418 555-0123" />
        </label>
      </div>

      <label className="block">
        <span className="klabel">Site web</span>
        <input className="field mt-[6px]" value={form.website} onChange={field("website", 300)} placeholder="https://…" />
      </label>

      <div>
        <p className="klabel">Réseaux sociaux</p>
        <div className="mt-2 grid gap-3 sm:grid-cols-2">
          {SOCIALS.map((s) => (
            <label key={s.key} className="block">
              <input
                className="field"
                value={form.socials[s.key] ?? ""}
                onChange={(e) =>
                  setForm({
                    ...form,
                    socials: { ...form.socials, [s.key]: e.target.value.slice(0, 200) },
                  })
                }
                placeholder={`${s.label} — ${s.placeholder}`}
              />
            </label>
          ))}
        </div>
      </div>

      {error && (
        <p className="rounded-md border-[1.5px] border-[#b3423a] bg-[#fbe9e7] px-4 py-3 text-[13px] font-medium text-[#7c2f2a]">
          {error}
        </p>
      )}
      <button type="button" className="btn btn-primary" disabled={saving} onClick={save}>
        {saved ? "✓ Enregistré" : saving ? "Enregistrement…" : "Enregistrer mon profil"}
      </button>
      <p className="gk-mono text-[10.5px] text-ink-3">
        Ces informations sont la source de vérité de votre profil sur TOUTES
        les plateformes ·Ka (Lou·Ka, Immo·Ka, Vrai-Prix…). Le courriel et le
        téléphone ne sont jamais affichés publiquement.
      </p>

      {/* ——— Profil public ——— */}
      <div className="border-t-[1.5px] border-dashed border-[rgba(20,24,20,0.25)] pt-5">
        <p className="gk-display text-[16px] font-bold uppercase">Profil public</p>
        <p className="mt-1 text-[13px] text-ink-2">
          Activez votre page publique pour partager votre profil — nom, photo,
          statut, bio, emploi, ville et réseaux sociaux.{" "}
          <strong>Jamais votre courriel ni votre téléphone.</strong>
        </p>
        <div className="mt-3 inline-flex overflow-hidden rounded-md border-[1.5px] border-ink" role="group">
          {([[false, "Privé"], [true, "Public"]] as const).map(([v, l]) => (
            <button
              key={l}
              type="button"
              onClick={() => togglePublic(v)}
              className={`px-5 py-2 text-[13px] font-bold transition-colors ${isPublic === v ? "bg-ink text-lime" : "bg-surface text-ink hover:bg-lime-soft"}`}
            >
              {l}
            </button>
          ))}
        </div>
        {isPublic && (
          <div className="mt-3 flex flex-wrap items-center gap-3 rounded-md border-[1.5px] border-green bg-lime-soft px-4 py-3">
            <a
              href={publicUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="gk-mono text-[12.5px] break-all text-green-deep underline underline-offset-4"
            >
              {publicUrl.replace("https://", "")}
            </a>
            <button
              type="button"
              className="btn btn-ghost !min-h-[34px] !px-3 !text-[12px]"
              onClick={async () => {
                try {
                  await navigator.clipboard.writeText(publicUrl);
                  setCopied(true);
                  setTimeout(() => setCopied(false), 1800);
                } catch {}
              }}
            >
              {copied ? "✓ Copié" : "Copier le lien"}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
