"use client";

import { useRef, useState, type FormEvent } from "react";
import { useRouter } from "next/navigation";
import { Icon } from "@/components/Icon";
import { api, ensureCsrf } from "@/lib/client";
import { useT } from "@/components/providers";

export interface MyProfileData {
  member: {
    public_uuid: string;
    full_name: string;
    id: number;
    membership_no: string | null;
    university: string | null;
    faculty: string | null;
    qualification: string | null;
    graduation_year: number | null;
    governorate_name: string | null;
    formal_status_ar: string;
    has_photo: boolean;
    has_phone: boolean;
    has_email: boolean;
  };
  affiliations: { id: number; kind: string; org_name: string; member_role: string | null; started_on: string | null; ended_on: string | null }[];
  externalPositions: { id: number; kind: string; org_name: string; title: string; started_on: string | null; ended_on: string | null }[];
  internalPositions: { id: number; title_ar: string; unit_name: string; started_on: string | null; ended_on: string | null }[];
  completion: { percent: number; missing: string[] };
}

const KIND_LABEL: Record<string, { ar: string; en: string }> = {
  syndicate: { ar: "نقابة", en: "Syndicate" },
  club: { ar: "نادي", en: "Club" },
  ngo: { ar: "جمعية/منظمة", en: "NGO" },
  university: { ar: "جامعة", en: "University" },
  other: { ar: "أخرى", en: "Other" },
  board: { ar: "عضو مجلس إدارة", en: "Board member" },
  council: { ar: "عضو مجلس", en: "Council member" },
};

export function MyProfileView({ initial }: { initial: MyProfileData }) {
  const { t, locale } = useT();
  const router = useRouter();
  const [data, setData] = useState(initial);
  const [message, setMessage] = useState<{ kind: "ok" | "err"; text: string } | null>(null);
  const [busy, setBusy] = useState(false);
  const fileRef = useRef<HTMLInputElement>(null);
  const m = data.member;

  async function reload() {
    const res = await api<MyProfileData>("/api/my");
    if (res.status === 200 && res.data) setData(res.data);
  }

  async function run(fn: () => Promise<{ status: number; error: string | null }>, okText: string) {
    setBusy(true);
    setMessage(null);
    const r = await fn();
    setBusy(false);
    if (r.status >= 200 && r.status < 300) {
      setMessage({ kind: "ok", text: okText });
      await reload();
    } else {
      setMessage({ kind: "err", text: r.error ?? t.myProfile.opFailed });
    }
  }

  async function saveEducation(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const f = new FormData(e.currentTarget);
    await run(
      () =>
        api("/api/my/education", "PUT", {
          university: String(f.get("university") ?? "").trim() || null,
          faculty: String(f.get("faculty") ?? "").trim() || null,
          qualification: String(f.get("qualification") ?? "").trim() || null,
          graduationYear: f.get("graduationYear") ? Number(f.get("graduationYear")) : null,
        }),
      t.myProfile.saved,
    );
  }

  async function uploadPhoto(file: File) {
    setBusy(true);
    setMessage(null);
    const csrf = await ensureCsrf();
    const res = await fetch(`/api/my/photo`, {
      method: "POST",
      headers: { "content-type": file.type || "image/jpeg", "x-csrf-token": csrf ?? "" },
      body: file,
      credentials: "same-origin",
    });
    setBusy(false);
    if (res.ok) {
      setMessage({ kind: "ok", text: t.myProfile.saved });
      await reload();
      router.refresh();
    } else {
      setMessage({ kind: "err", text: t.myProfile.opFailed });
    }
  }

  async function removePhoto() {
    const csrf = await ensureCsrf();
    setBusy(true);
    const res = await fetch(`/api/my/photo`, {
      method: "DELETE",
      headers: { "x-csrf-token": csrf ?? "" },
      credentials: "same-origin",
    });
    setBusy(false);
    if (res.ok) {
      setMessage({ kind: "ok", text: t.myProfile.saved });
      await reload();
      router.refresh();
    }
  }

  const kindLabel = (k: string) => (locale === "ar" ? KIND_LABEL[k]?.ar ?? k : KIND_LABEL[k]?.en ?? k);
  const missingLabels: Record<string, { ar: string; en: string }> = {
    full_name: { ar: "الاسم", en: "name" },
    governorate: { ar: "المحافظة", en: "governorate" },
    membership_no: { ar: "رقم العضوية", en: "membership no." },
    phone: { ar: "الهاتف", en: "phone" },
    photo: { ar: "الصورة", en: "photo" },
    education: { ar: "التعليم", en: "education" },
    affiliations: { ar: "العضويات", en: "affiliations" },
  };

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-extrabold text-slate-900" dir="auto">{t.myProfile.title}</h1>

      {message && (
        <div role="status" className={`rounded-lg border px-4 py-2.5 text-sm ${message.kind === "ok" ? "border-emerald-200 bg-emerald-50 text-emerald-800" : "border-red-200 bg-red-50 text-red-700"}`}>
          {message.text}
        </div>
      )}

      {/* completion progress */}
      <section className="rounded-xl border border-slate-200 bg-white p-6 shadow-card">
        <div className="flex flex-wrap items-center justify-between gap-2">
          <h2 className="font-bold text-slate-900">{t.myProfile.completion}</h2>
          <span className="numeric text-sm font-bold text-bousla-700">{data.completion.percent}%</span>
        </div>
        <div className="mt-3 h-2.5 overflow-hidden rounded-full bg-slate-100">
          <div className="h-full rounded-full bg-bousla-600 transition-all" style={{ width: `${data.completion.percent}%` }} />
        </div>
        {data.completion.missing.length > 0 && (
          <p className="mt-2 text-xs text-slate-500">
            {t.myProfile.recommendedMissing}: {data.completion.missing.map((k) => (locale === "ar" ? missingLabels[k]?.ar ?? k : missingLabels[k]?.en ?? k)).join(" · ")}
          </p>
        )}
      </section>

      {/* basic info + photo */}
      <section className="rounded-xl border border-slate-200 bg-white p-6 shadow-card">
        <h2 className="mb-4 flex items-center gap-2 font-bold text-slate-900">
          <Icon name="user" className="h-5 w-5 text-bousla-700" /> {t.myProfile.basicInfo}
        </h2>
        <div className="flex flex-wrap items-start gap-6">
          <div className="text-center">
            {m.has_photo ? (
              // eslint-disable-next-line @next/next/no-img-element
              <img src={`/api/members/${m.public_uuid}/photo?v=${Date.now()}`} alt={m.full_name} className="h-28 w-28 rounded-xl object-cover ring-1 ring-slate-200" />
            ) : (
              <span className="grid h-28 w-28 place-items-center rounded-xl bg-slate-100 text-3xl text-slate-400">{m.full_name.trim().slice(0, 1)}</span>
            )}
            <input
              ref={fileRef}
              type="file"
              accept="image/jpeg,image/png,image/webp"
              className="hidden"
              onChange={(e) => { const f = e.target.files?.[0]; if (f) void uploadPhoto(f); e.target.value = ""; }}
            />
            <div className="mt-2 flex flex-col gap-1">
              <button type="button" disabled={busy} onClick={() => fileRef.current?.click()} className="text-xs font-bold text-bousla-700 hover:underline disabled:opacity-50">
                {t.myProfile.uploadPhoto}
              </button>
              {m.has_photo && (
                <button type="button" disabled={busy} onClick={() => void removePhoto()} className="text-xs font-bold text-red-600 hover:underline disabled:opacity-50">
                  {t.myProfile.removePhoto}
                </button>
              )}
            </div>
          </div>
          <dl className="grid flex-1 grid-cols-2 gap-x-8 gap-y-2 text-sm sm:grid-cols-3">
            <div><dt className="text-xs text-slate-400">{t.members.fullName}</dt><dd className="font-semibold text-slate-700" dir="auto">{m.full_name}</dd></div>
            <div><dt className="text-xs text-slate-400">{t.members.systemNo}</dt><dd className="numeric font-semibold text-slate-700" dir="ltr">{m.id}</dd></div>
            <div><dt className="text-xs text-slate-400">{t.members.membershipNo}</dt><dd className="numeric font-semibold text-slate-700" dir="ltr">{m.membership_no ?? "—"}</dd></div>
            <div><dt className="text-xs text-slate-400">{t.members.governorate}</dt><dd className="font-semibold text-slate-700">{m.governorate_name ?? "—"}</dd></div>
            <div><dt className="text-xs text-slate-400">{t.members.formalStatus}</dt><dd className="font-semibold text-slate-700">{m.formal_status_ar}</dd></div>
            <div><dt className="text-xs text-slate-400">{t.members.contact}</dt><dd className="font-semibold text-slate-700">{m.has_phone || m.has_email ? (locale === "ar" ? "مسجلة (مقنعة)" : "on file (masked)") : t.members.notRecorded}</dd></div>
          </dl>
        </div>
        <p className="mt-3 text-[11px] text-slate-400">{t.myProfile.photoHint}</p>
      </section>

      {/* internal union positions (read-only, staff-documented) */}
      {data.internalPositions.length > 0 && (
        <section className="rounded-xl border border-slate-200 bg-white p-6 shadow-card">
          <h2 className="mb-4 flex items-center gap-2 font-bold text-slate-900">
            <Icon name="sitemap" className="h-5 w-5 text-bousla-700" /> {t.myProfile.internalPositions}
          </h2>
          <ul className="space-y-2">
            {data.internalPositions.map((p) => (
              <li key={p.id} className={"rounded-lg border border-slate-100 px-4 py-2.5 text-sm " + (p.ended_on ? "bg-slate-50/60 opacity-75" : "bg-white")}>
                <b dir="auto">{p.title_ar}</b> — {p.unit_name}{p.started_on ? ` · ${t.myProfile.from} ${p.started_on}` : ""}{p.ended_on ? ` · ${t.myProfile.to} ${p.ended_on}` : ""}
              </li>
            ))}
          </ul>
        </section>
      )}

      {/* education */}
      <section className="rounded-xl border border-slate-200 bg-white p-6 shadow-card">
        <h2 className="mb-4 flex items-center gap-2 font-bold text-slate-900">
          <Icon name="academic" className="h-5 w-5 text-bousla-700" /> {t.myProfile.education}
        </h2>
        <form onSubmit={saveEducation} className="grid gap-4 sm:grid-cols-2">
          <div><label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="edu-u">{t.myProfile.university}</label><input id="edu-u" name="university" defaultValue={m.university ?? ""} maxLength={200} dir="auto" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" /></div>
          <div><label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="edu-f">{t.myProfile.faculty}</label><input id="edu-f" name="faculty" defaultValue={m.faculty ?? ""} maxLength={200} dir="auto" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" /></div>
          <div><label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="edu-q">{t.myProfile.qualification}</label><input id="edu-q" name="qualification" defaultValue={m.qualification ?? ""} maxLength={200} dir="auto" className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" /></div>
          <div><label className="mb-1 block text-xs font-bold text-slate-600" htmlFor="edu-y">{t.myProfile.graduationYear}</label><input id="edu-y" name="graduationYear" type="number" min={1950} max={2100} defaultValue={m.graduation_year ?? ""} className="w-full rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500 focus:ring-2 focus:ring-bousla-100" /></div>
          <div className="sm:col-span-2"><button type="submit" disabled={busy} className="rounded-lg bg-bousla-700 px-4 py-2 text-sm font-bold text-white hover:bg-bousla-800 disabled:opacity-60">{t.myProfile.saveEducation}</button></div>
        </form>
      </section>

      {/* affiliations (membership) */}
      <section className="rounded-xl border border-slate-200 bg-white p-6 shadow-card">
        <h2 className="font-bold text-slate-900">{t.myProfile.affiliations}</h2>
        <p className="mt-1 text-xs text-slate-400">{t.myProfile.affiliationsHint}</p>
        <ul className="mt-4 space-y-2">
          {data.affiliations.map((a) => (
            <li key={a.id} className="flex items-center justify-between gap-3 rounded-lg border border-slate-100 bg-slate-50/60 px-4 py-2.5 text-sm">
              <span><b dir="auto">{a.org_name}</b> · {kindLabel(a.kind)}{a.member_role ? ` · ${a.member_role}` : ""}{a.started_on ? ` · ${t.myProfile.from} ${a.started_on}` : ""}</span>
              <button type="button" disabled={busy} onClick={() => void run(() => api(`/api/my/affiliations/${a.id}`, "DELETE"), t.myProfile.saved)} className="text-xs font-bold text-red-600 hover:underline disabled:opacity-50">{t.myProfile.delete}</button>
            </li>
          ))}
          {data.affiliations.length === 0 && <li className="text-sm text-slate-400">—</li>}
        </ul>
        <form
          className="mt-4 grid gap-3 border-t border-slate-100 pt-4 sm:grid-cols-2"
          onSubmit={(e) => {
            e.preventDefault();
            const f = new FormData(e.currentTarget);
            void run(
              () =>
                api("/api/my/affiliations", "POST", {
                  kind: String(f.get("kind")),
                  orgName: String(f.get("orgName") ?? "").trim(),
                  memberRole: String(f.get("memberRole") ?? "").trim() || null,
                  startedOn: String(f.get("startedOn") ?? "") || null,
                }),
              t.myProfile.saved,
            ).then(() => (e.target as HTMLFormElement).reset());
          }}
        >
          <input name="orgName" required minLength={2} maxLength={200} placeholder={t.myProfile.orgName} dir="auto" className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500" />
          <select name="kind" className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm outline-none focus:border-bousla-500">
            <option value="syndicate">{t.myProfile.syndicate}</option>
            <option value="club">{t.myProfile.club}</option>
            <option value="ngo">{t.myProfile.ngo}</option>
            <option value="university">{t.myProfile.universityKind}</option>
            <option value="other">{t.myProfile.other}</option>
          </select>
          <input name="memberRole" maxLength={150} placeholder={t.myProfile.memberRole} dir="auto" className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500" />
          <input name="startedOn" type="date" className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500" />
          <div className="sm:col-span-2"><button type="submit" disabled={busy} className="rounded-lg border border-bousla-200 px-4 py-2 text-sm font-bold text-bousla-800 hover:bg-bousla-50 disabled:opacity-60">{t.myProfile.addAffiliation}</button></div>
        </form>
      </section>

      {/* external positions (office) */}
      <section className="rounded-xl border border-slate-200 bg-white p-6 shadow-card">
        <h2 className="font-bold text-slate-900">{t.myProfile.externalPositions}</h2>
        <p className="mt-1 text-xs text-slate-400">{t.myProfile.externalPositionsHint}</p>
        <ul className="mt-4 space-y-2">
          {data.externalPositions.map((p) => (
            <li key={p.id} className="flex items-center justify-between gap-3 rounded-lg border border-slate-100 bg-slate-50/60 px-4 py-2.5 text-sm">
              <span><b dir="auto">{p.title}</b> — {p.org_name} · {kindLabel(p.kind)}{p.started_on ? ` · ${t.myProfile.from} ${p.started_on}` : ""}{p.ended_on ? ` · ${t.myProfile.to} ${p.ended_on}` : ""}</span>
              <button type="button" disabled={busy} onClick={() => void run(() => api(`/api/my/external-positions/${p.id}`, "DELETE"), t.myProfile.saved)} className="text-xs font-bold text-red-600 hover:underline disabled:opacity-50">{t.myProfile.delete}</button>
            </li>
          ))}
          {data.externalPositions.length === 0 && <li className="text-sm text-slate-400">—</li>}
        </ul>
        <form
          className="mt-4 grid gap-3 border-t border-slate-100 pt-4 sm:grid-cols-2"
          onSubmit={(e) => {
            e.preventDefault();
            const f = new FormData(e.currentTarget);
            void run(
              () =>
                api("/api/my/external-positions", "POST", {
                  orgName: String(f.get("orgName") ?? "").trim(),
                  title: String(f.get("title") ?? "").trim(),
                  kind: String(f.get("kind")),
                  startedOn: String(f.get("startedOn") ?? "") || null,
                }),
              t.myProfile.saved,
            ).then(() => (e.target as HTMLFormElement).reset());
          }}
        >
          <input name="orgName" required minLength={2} maxLength={200} placeholder={t.myProfile.orgName} dir="auto" className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500" />
          <input name="title" required minLength={2} maxLength={150} placeholder={t.myProfile.positionTitle} dir="auto" className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500" />
          <select name="kind" className="rounded-lg border border-slate-300 bg-white px-3 py-2 text-sm outline-none focus:border-bousla-500">
            <option value="board">{t.myProfile.board}</option>
            <option value="council">{t.myProfile.council}</option>
            <option value="other">{t.myProfile.otherKind}</option>
          </select>
          <input name="startedOn" type="date" className="rounded-lg border border-slate-300 px-3 py-2 text-sm outline-none focus:border-bousla-500" />
          <div className="sm:col-span-2"><button type="submit" disabled={busy} className="rounded-lg border border-bousla-200 px-4 py-2 text-sm font-bold text-bousla-800 hover:bg-bousla-50 disabled:opacity-60">{t.myProfile.addExternal}</button></div>
        </form>
      </section>
    </div>
  );
}
