"use client";

import { useMemo, useState } from "react";
import { useLang } from "@/context/LanguageContext";
import { Button, Card, EmptyState, PageHeader, LoadingArea } from "@/components/ui";
import { useApi } from "@/lib/client";
import { formatDate } from "@/lib/utils";
import { IconCard, IconFile } from "@/components/icons";
import { openPrintWindow } from "@/lib/print";

import {
  DEFAULT_ID_FIELDS,
  idCardHtml as buildIdCard,
  idCardPrintHtml,
  type DesignId,
  type IdCardStudent,
} from "@/lib/id-card";

interface MyStudent {
  student: {
    id: number;
    roll: string;
    registrationNo: string | null;
    cardNo: string | null;
    cardIssuedAt: string | null;
    cardValidTill: string | null;
    bloodGroup: string | null;
    name: string;
    nameBn: string | null;
    gender: string;
    dob: string | null;
    guardianName: string;
    guardianPhone: string;
    address: string | null;
    photoUrl: string | null;
    className: string | null;
    classNameBn: string | null;
    sectionName: string | null;
  } | null;
  institution: { name: string; address: string; phone: string; website: string | null; logo: string | null } | null;
}

/** Student/parent: their own ID card, rendered with the exact designs the
    institution portal prints (Certificates → ID Card) — switch designs and
    print a copy identical to the institutional one. */
export default function MeIdCardPage() {
  const { t, locale } = useLang();
  const { data, loading } = useApi<MyStudent>("/api/me/student");
  const [design, setDesign] = useState<DesignId>(1);
  const L = t.portal.certificatesPage;

  const s = data?.student ?? null;
  const inst = data?.institution ?? null;

  /** map the profile onto the shared card builder's input */
  const cardStudent: IdCardStudent | null = useMemo(() => {
    if (!s) return null;
    return {
      id: s.id,
      roll: s.roll,
      name: s.name,
      nameBn: s.nameBn,
      gender: s.gender ?? "MALE",
      dob: s.dob ?? null,
      guardianName: s.guardianName ?? "",
      guardianPhone: s.guardianPhone ?? "",
      address: s.address ?? null,
      className: s.className,
      sectionName: s.sectionName,
      shiftName: null,
      groupName: null,
      cardNo: s.cardNo,
      registrationNo: s.registrationNo,
      bloodGroup: s.bloodGroup,
      cardValidTill: s.cardValidTill,
    };
  }, [s]);

  const cardHtml = useMemo(() => {
    if (!cardStudent || !inst) return "";
    return buildIdCard({
      st: cardStudent,
      inst,
      design,
      fields: { ...DEFAULT_ID_FIELDS },
      labels: L,
      locale,
    });
  }, [cardStudent, inst, design, L, locale]);

  function printCard() {
    if (!cardHtml) return;
    openPrintWindow(L.studentIdCard, locale, idCardPrintHtml([cardHtml], design, t.landing.poweredBy));
  }

  if (loading) {
    return (
      <div>
        <PageHeader title={t.me.idCardTitle} subtitle={t.me.idCardSubtitle} />
        <LoadingArea label={t.common.loading} />
      </div>
    );
  }

  if (!s) {
    return (
      <div>
        <PageHeader title={t.me.idCardTitle} subtitle={t.me.idCardSubtitle} />
        <div className="card">
          <EmptyState icon={<IconCard />} title={t.portal.myProfilePage.notLinked} />
        </div>
      </div>
    );
  }

  const initials = s.name
    .split(" ")
    .map((w) => w[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();

  const rows: [string, string][] = [
    [t.portal.identityPage.roll, s.roll],
    [t.portal.studentsPage.classLabel, locale === "bn" && s.classNameBn ? s.classNameBn : s.className ?? "—"],
    [t.portal.identityPage.registrationNo, s.registrationNo ?? "—"],
    [t.portal.identityPage.cardNo, s.cardNo ?? "—"],
    [t.portal.identityPage.bloodGroup, s.bloodGroup ?? "—"],
    [t.portal.identityPage.cardValidTill, s.cardValidTill ? formatDate(s.cardValidTill, locale) : "—"],
  ];

  const designChoices: { id: DesignId; label: string }[] = [
    { id: 1, label: L.designClassic },
    { id: 2, label: L.designModern },
    { id: 3, label: L.designSide },
    { id: 4, label: L.designFrame },
  ];

  return (
    <div>
      <PageHeader title={t.me.idCardTitle} subtitle={t.me.idCardSubtitle} />

      <div className="row g-4">
        <div className="col-xl-7">
          <Card title={t.me.idCardTitle} icon={<IconCard className="svg-20" />}>
            {/* design picker — the same 4 designs the institution prints */}
            <p className="f-w-700 ems-fs-13 mb-2">{L.designLabel}</p>
            <div className="d-flex flex-wrap gap-2 mb-3">
              {designChoices.map((d) => (
                <button
                  key={d.id}
                  type="button"
                  className={`btn btn-sm ${design === d.id ? "btn-primary" : "btn-outline-primary"}`}
                  onClick={() => setDesign(d.id)}
                >
                  {d.id}. {d.label}
                </button>
              ))}
            </div>
            <div className="d-flex flex-wrap justify-content-center align-items-start" style={{ background: "#f4f7fa", borderRadius: 10, padding: 20, minHeight: 300 }}>
              {cardHtml ? <div dangerouslySetInnerHTML={{ __html: cardHtml }} /> : null}
            </div>
            <div className="d-flex justify-content-end pt-3">
              <Button onClick={printCard} disabled={!cardHtml}>
                <IconFile className="svg-16" />
                <span className="ms-1">{t.portal.certificatesPage.print}</span>
              </Button>
            </div>
            <p className="ems-fs-11 text-muted mt-3 mb-0">{t.me.idCardHint}</p>
          </Card>
        </div>

        <div className="col-xl-5">
          <Card title={t.me.idCardDataTitle} icon={<IconCard className="svg-20" />}>
            <div className="d-flex gap-3 mb-3">
              {s.photoUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={s.photoUrl}
                  alt={s.name}
                  style={{ width: 72, height: 72, objectFit: "cover" }}
                  className="rounded-circle border flex-shrink-0"
                />
              ) : (
                <div
                  className="rounded-circle d-flex align-items-center justify-content-center flex-shrink-0"
                  style={{ width: 72, height: 72, background: "rgba(36,105,92,0.15)", color: "#24695c", fontSize: 24, fontWeight: 800 }}
                >
                  {initials}
                </div>
              )}
              <div className="min-w-0">
                <h6 className="mb-0 f-w-800">{s.name}</h6>
                <p className="ems-fs-12 text-muted mb-0">
                  {locale === "bn" && s.classNameBn ? s.classNameBn : s.className ?? ""}
                  {s.sectionName ? ` · ${s.sectionName}` : ""}
                </p>
              </div>
            </div>
            <div className="table-responsive">
              <table className="table table-sm mb-0">
                <tbody>
                  {rows.map(([k, v]) => (
                    <tr key={k}>
                      <td className="ems-fs-12 text-muted" style={{ width: "45%", border: 0 }}>{k}</td>
                      <td className="ems-fs-13 f-w-700" style={{ border: 0 }}>{v}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <p className="ems-fs-11 text-muted mt-3 mb-0">{t.me.idCardDataHint}</p>
          </Card>
        </div>
      </div>
    </div>
  );
}
