"use client";

import { useEffect, useState, useCallback } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import Card, { CardHeader } from "@/components/ui/Card";
import Button from "@/components/ui/Button";
import Modal from "@/components/ui/Modal";
import Spinner from "@/components/ui/Spinner";
import { Field } from "@/components/ui/Input";
import { Select } from "@/components/ui/Select";
import { Table, Td, EmptyRow } from "@/components/ui/Table";
import { useToast } from "@/components/ui/Toast";
import { formatDate } from "@/lib/format";
import { FileBadge, Eye, Plus, Printer, Download, Award } from "lucide-react";

type Program = { id: string; title: string; venue: string | null; start_at: string };
type Cert = {
  id: string;
  issued_at: string;
  volunteer: string;
  matric_no: string | null;
  program: string | null;
  venue: string | null;
  volunteer_id?: string;
};
type Approved = { volunteer_id: string; full_name: string };

// Template image: certificate_template.png (1414 x 2000 px, A4 portrait
// ratio). This is the FULL BLEED version — the original Canva export used
// as-is with zero padding, so the design touches all four page edges
// exactly like the source file. All dynamic text below is centered on the
// "SIJIL PENYERTAAN" title's visual center (46.15% of width — measured
// directly from the template, since the gold corner decoration shifts the
// design's visual balance slightly left of the page's true 50% center).
const LAYOUT = {
  pageWidthMm: 210,
  pageHeightMm: 297,
  centerXPct: 46.15,
  nameYPct: 42.0,
  matricYPct: 46.3,
  roleYPct: 55.5,
  programYPct: 63.5,
  venueYPct: 71.0,
};

const DETAIL_FONT_SIZE = 15;
const NAME_FONT_SIZE = 22;

async function downloadCertificate(cert: Cert) {
  const { jsPDF } = await import("jspdf");
  const doc = new jsPDF({ orientation: "portrait", unit: "mm", format: "a4" });
  const W = LAYOUT.pageWidthMm;
  const H = LAYOUT.pageHeightMm;
  const cx = (LAYOUT.centerXPct / 100) * W;

  doc.addImage("/certificate_template.png", "PNG", 0, 0, W, H);

  const ink: [number, number, number] = [40, 32, 20];
  const gold: [number, number, number] = [150, 116, 45];

  doc.setFont("helvetica", "bold");
  doc.setFontSize(NAME_FONT_SIZE);
  doc.setTextColor(...gold);
  doc.text(cert.volunteer, cx, (LAYOUT.nameYPct / 100) * H, { align: "center" });

  doc.setFont("helvetica", "bold");
  doc.setFontSize(DETAIL_FONT_SIZE);
  doc.setTextColor(...ink);

  if (cert.matric_no) {
    doc.text(cert.matric_no, cx, (LAYOUT.matricYPct / 100) * H, { align: "center" });
  }

  doc.text("PESERTA", cx, (LAYOUT.roleYPct / 100) * H, { align: "center" });

  doc.text(cert.program ?? "Pusat Islam programs", cx, (LAYOUT.programYPct / 100) * H, {
    align: "center",
    maxWidth: W - 40,
  });

  doc.text(cert.venue ?? "Pusat Islam, UPSI", cx, (LAYOUT.venueYPct / 100) * H, {
    align: "center",
    maxWidth: W - 40,
  });

  const safeName = cert.volunteer.replace(/[^a-z0-9]+/gi, "_").toLowerCase();
  doc.save(`sijil_${safeName}.pdf`);
}

function useIsMobileViewport() {
  const [isMobile, setIsMobile] = useState(false);
  useEffect(() => {
    const check = () => setIsMobile(window.innerWidth < 768);
    check();
    window.addEventListener("resize", check);
    return () => window.removeEventListener("resize", check);
  }, []);
  return isMobile;
}

export default function CertificatesPage() {
  const supabase = createClient();
  const searchParams = useSearchParams();
  const router = useRouter();
  const { notify } = useToast();
  const isViewportMobile = useIsMobileViewport();
  const isPreviewMobile = searchParams.get("preview") === "mobile";
  const isMobile = isViewportMobile || isPreviewMobile;

  const [loading, setLoading] = useState(true);
  const [userRole, setUserRole] = useState<"admin" | "volunteer">("volunteer");
  const [userId, setUserId] = useState("");

  const [certs, setCerts] = useState<Cert[]>([]);
  const [programs, setPrograms] = useState<Program[]>([]);
  const [saving, setSaving] = useState(false);

  const [genOpen, setGenOpen] = useState(false);
  const [programId, setProgramId] = useState("");
  const [approved, setApproved] = useState<Approved[]>([]);
  const [volunteerId, setVolunteerId] = useState("");

  const [preview, setPreview] = useState<Cert | null>(null);

  const load = useCallback(async () => {
    const { data: userRes } = await supabase.auth.getUser();
    if (!userRes.user) {
      router.push("/login");
      return;
    }
    setUserId(userRes.user.id);

    const { data: profile } = await supabase
      .from("profiles")
      .select("role")
      .eq("id", userRes.user.id)
      .single();

    if (!profile) return;
    setUserRole(profile.role);

    if (profile.role === "admin") {
      const [c, p] = await Promise.all([
        supabase
          .from("certificates")
          .select(
            "id, volunteer_id, issued_at, profiles!volunteer_id(full_name, matric_no), programs(title, venue)"
          )
          .order("issued_at", { ascending: false }),
        supabase.from("programs").select("id, title, venue, start_at").order("start_at", { ascending: false }),
      ]);
      setCerts(
        (c.data ?? []).map((x: any) => ({
          id: x.id,
          issued_at: x.issued_at,
          volunteer: x.profiles?.full_name ?? "Unknown",
          matric_no: x.profiles?.matric_no ?? null,
          program: x.programs?.title ?? null,
          venue: x.programs?.venue ?? null,
          volunteer_id: x.volunteer_id,
        }))
      );
      setPrograms((p.data as Program[]) ?? []);
    } else {
      const { data } = await supabase
        .from("certificates")
        .select(
          "id, volunteer_id, issued_at, profiles!volunteer_id(full_name, matric_no), programs(title, venue)"
        )
        .eq("volunteer_id", userRes.user.id)
        .order("issued_at", { ascending: false });

      setCerts(
        (data ?? []).map((x: any) => ({
          id: x.id,
          issued_at: x.issued_at,
          volunteer: x.profiles?.full_name ?? "Unknown",
          matric_no: x.profiles?.matric_no ?? null,
          program: x.programs?.title ?? null,
          venue: x.programs?.venue ?? null,
          volunteer_id: x.volunteer_id,
        }))
      );
    }
    setLoading(false);
  }, [supabase, router]);

  useEffect(() => {
    load();
  }, [load]);

  useEffect(() => {
    if (!programId) {
      setApproved([]);
      return;
    }
    (async () => {
      const { data } = await supabase
        .from("applications")
        .select("volunteer_id, profiles!volunteer_id(full_name)")
        .eq("program_id", programId)
        .eq("status", "approved");
      setApproved(
        (data ?? []).map((a: any) => ({ volunteer_id: a.volunteer_id, full_name: a.profiles?.full_name ?? "Unknown" }))
      );
      setVolunteerId("");
    })();
  }, [programId, supabase]);

  async function generate(e: React.FormEvent) {
    e.preventDefault();
    if (!programId || !volunteerId) return notify("Select a program and volunteer.", "error");
    setSaving(true);
    const { error } = await supabase.from("certificates").insert({
      volunteer_id: volunteerId,
      program_id: programId,
      issued_by: userId,
    });
    setSaving(false);
    if (error) return notify(error.message, "error");
    notify("Certificate generated.");
    setGenOpen(false);
    setProgramId("");
    setVolunteerId("");
    load();
  }

  if (loading) return <Spinner label="Loading certificates…" />;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className={`${isMobile ? "text-xl font-bold" : "text-2xl font-extrabold"} text-ink`}>
            {userRole === "admin" ? "Manage Certificates" : "My Certificates"}
          </h1>
          <p className="text-sm text-muted">
            {userRole === "admin"
              ? "Issue Sijil Penyertaan to volunteers who completed programs."
              : "View and download your Sijil Penyertaan (certificate of participation)."}
          </p>
        </div>
        {userRole === "admin" && (
          <Button onClick={() => setGenOpen(true)}>
            <Plus size={16} /> Generate certificate
          </Button>
        )}
      </div>

      {isMobile ? (
        <div className="space-y-3">
          {certs.length > 0 ? (
            certs.map((c) => (
              <div key={c.id} className="rounded-card border border-sand-dark/60 bg-white p-4 shadow-card flex justify-between items-center">
                <div>
                  <h3 className="text-sm font-bold text-ink leading-snug">{c.program ?? "Volunteer Appreciation"}</h3>
                  {userRole === "admin" && <p className="text-xs text-muted">Volunteer: {c.volunteer}</p>}
                  <p className="mt-1 text-[10px] text-muted">Issued: {formatDate(c.issued_at)}</p>
                </div>
                <div className="flex gap-1.5">
                  <button
                    onClick={() => setPreview(c)}
                    className="rounded-card bg-sand p-2 text-muted hover:text-emerald"
                    title="Preview"
                  >
                    <Eye size={16} />
                  </button>
                  <button
                    onClick={() => downloadCertificate(c)}
                    className="rounded-card bg-emerald-light p-2 text-emerald hover:bg-emerald hover:text-white transition-colors"
                    title="Download PDF"
                  >
                    <Download size={16} />
                  </button>
                </div>
              </div>
            ))
          ) : (
            <p className="text-center py-10 text-xs text-muted">No certificates found.</p>
          )}
        </div>
      ) : (
        <Card>
          <CardHeader title={userRole === "admin" ? `Issued certificates (${certs.length})` : `My certificates (${certs.length})`} />
          <Table headers={userRole === "admin" ? ["Volunteer", "Program", "Issued", ""] : ["Program", "Issued Date", ""]}>
            {certs.length ? (
              certs.map((c) => (
                <tr key={c.id} className="hover:bg-sand/40">
                  {userRole === "admin" && <Td className="font-semibold">{c.volunteer}</Td>}
                  <Td className="font-semibold">{c.program ?? "—"}</Td>
                  <Td>{formatDate(c.issued_at)}</Td>
                  <Td>
                    <div className="flex justify-end gap-2">
                      <Button size="sm" variant="secondary" onClick={() => setPreview(c)}>
                        <Eye size={14} /> Preview
                      </Button>
                      <Button size="sm" onClick={() => downloadCertificate(c)}>
                        <Download size={14} /> PDF
                      </Button>
                    </div>
                  </Td>
                </tr>
              ))
            ) : (
              <EmptyRow colSpan={userRole === "admin" ? 4 : 3} message="No certificates found." />
            )}
          </Table>
        </Card>
      )}

      {userRole === "admin" && (
        <Modal open={genOpen} onClose={() => setGenOpen(false)} title="Generate certificate">
          <form onSubmit={generate} className="space-y-4">
            <Field label="Program">
              <Select value={programId} onChange={(e) => setProgramId(e.target.value)}>
                <option value="">Select a program…</option>
                {programs.map((p) => (
                  <option key={p.id} value={p.id}>
                    {p.title}
                  </option>
                ))}
              </Select>
            </Field>
            <Field label="Volunteer" hint="Only approved applicants for the selected program are shown.">
              <Select value={volunteerId} onChange={(e) => setVolunteerId(e.target.value)} disabled={!programId}>
                <option value="">{programId ? "Select a volunteer…" : "Choose a program first"}</option>
                {approved.map((a) => (
                  <option key={a.volunteer_id} value={a.volunteer_id}>
                    {a.full_name}
                  </option>
                ))}
              </Select>
              {programId && !approved.length && (
                <p className="mt-1 text-xs text-warning">No approved volunteers for this program yet.</p>
              )}
            </Field>
            <div className="flex justify-end gap-2 pt-2">
              <Button type="button" variant="secondary" onClick={() => setGenOpen(false)}>
                Cancel
              </Button>
              <Button type="submit" disabled={saving}>
                {saving ? "Generating…" : "Generate"}
              </Button>
            </div>
          </form>
        </Modal>
      )}

      <Modal open={!!preview} onClose={() => setPreview(null)} title="Certificate preview" wide>
        {preview && (
          <div className="space-y-4">
            <div
              id="cert-print"
              className="relative mx-auto overflow-hidden rounded-card border border-sand-dark/40 shadow-md"
              style={{ width: "100%", maxWidth: 480, aspectRatio: "1414 / 2000" }}
            >
              <img
                src="/certificate_template.png"
                alt="Certificate template"
                className="absolute inset-0 h-full w-full object-cover"
              />
              <div
                className="absolute -translate-x-1/2 text-center px-6 font-bold whitespace-nowrap"
                style={{ left: "46.15%", top: "42.0%", color: "#96742d", fontSize: "5%" }}
              >
                {preview.volunteer}
              </div>
              {preview.matric_no && (
                <div
                  className="absolute -translate-x-1/2 text-center px-6 font-bold whitespace-nowrap"
                  style={{ left: "46.15%", top: "46.3%", color: "#281f14", fontSize: "3.4%" }}
                >
                  {preview.matric_no}
                </div>
              )}
              <div
                className="absolute -translate-x-1/2 text-center px-6 font-bold whitespace-nowrap"
                style={{ left: "46.15%", top: "55.5%", color: "#281f14", fontSize: "3.4%" }}
              >
                PESERTA
              </div>
              <div
                className="absolute -translate-x-1/2 text-center px-8 font-bold"
                style={{ left: "46.15%", top: "63.5%", color: "#281f14", fontSize: "3.4%", maxWidth: "80%" }}
              >
                {preview.program ?? "Pusat Islam programs"}
              </div>
              <div
                className="absolute -translate-x-1/2 text-center px-8 font-bold"
                style={{ left: "46.15%", top: "71.0%", color: "#281f14", fontSize: "3.4%", maxWidth: "80%" }}
              >
                {preview.venue ?? "Pusat Islam, UPSI"}
              </div>
            </div>
            <div className="flex justify-end gap-2">
              <Button variant="secondary" onClick={() => window.print()}>
                <Printer size={16} /> Print
              </Button>
              <Button onClick={() => downloadCertificate(preview)}>
                <Download size={16} /> Download PDF
              </Button>
            </div>
          </div>
        )}
      </Modal>

      <style>{`
        @media print {
          body * { visibility: hidden; }
          #cert-print, #cert-print * { visibility: visible; }
          #cert-print { position: fixed; inset: 0; margin: auto; width: 90%; }
        }
      `}</style>
    </div>
  );
}