"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";

type SalarieImpression = {
  cos: number;
  nom: string;
  prenom: string;
};

type SecteurImpression = {
  id: number;
  secteur: string;
  salaries: SalarieImpression[];
};

type SalariesEnCoursReport = {
  generatedAt: string;
  secteurs: SecteurImpression[];
  totalSalaries: number;
  salariesSansSecteur: number;
};

function formatDate(date: string) {
  return new Date(date).toLocaleDateString("fr-FR", {
    timeZone: "Europe/Paris",
  });
}

export default function SalariesEnCoursPrintPage() {
  const router = useRouter();
  const [report, setReport] = useState<SalariesEnCoursReport | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    async function fetchReport() {
      const token = localStorage.getItem("token");

      if (!token) {
        router.push("/login");
        return;
      }

      try {
        const response = await fetch(
          `${process.env.NEXT_PUBLIC_API_URL}/api/impressions/salaries-en-cours`,
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
            cache: "no-store",
          },
        );

        if (response.status === 401) {
          localStorage.removeItem("token");
          localStorage.removeItem("user");
          router.push("/login");
          return;
        }

        const data = await response.json().catch(() => null);

        if (!response.ok) {
          throw new Error(
            data?.message ?? "Impossible de charger le rapport.",
          );
        }

        setReport(data.report);
      } catch (caughtError) {
        setError(
          caughtError instanceof Error
            ? caughtError.message
            : "Une erreur inattendue est survenue.",
        );
      } finally {
        setLoading(false);
      }
    }

    void fetchReport();
  }, [router]);

  if (loading) {
    return (
      <main className="flex min-h-screen items-center justify-center bg-slate-100 text-slate-700">
        Génération de la liste des salariés en cours...
      </main>
    );
  }

  if (error || !report) {
    return (
      <main className="flex min-h-screen flex-col items-center justify-center gap-4 bg-slate-100 p-6">
        <p className="rounded border border-red-300 bg-red-50 p-4 text-red-700">
          {error ?? "Rapport indisponible."}
        </p>
        <button
          type="button"
          onClick={() => router.back()}
          className="rounded bg-blue-600 px-4 py-2 font-semibold text-white"
        >
          Retour
        </button>
      </main>
    );
  }

  return (
    <main className="print-report min-h-screen bg-slate-200 py-6 text-black">
      <div className="screen-toolbar mx-auto mb-5 flex max-w-[210mm] items-center justify-between rounded bg-white p-4 shadow">
        <div>
          <h1 className="font-bold text-slate-900">
            Liste des salariés en cours
          </h1>
          <p className="text-sm text-slate-600">
            {report.secteurs.length} secteur(s) — {report.totalSalaries} salarié(s)
          </p>
          {report.salariesSansSecteur > 0 && (
            <p className="mt-1 text-sm font-semibold text-amber-700">
              Attention : {report.salariesSansSecteur} salarié(s) actif(s)
              n&apos;ont pas de secteur reconnu.
            </p>
          )}
        </div>

        <div className="flex gap-2">
          <button
            type="button"
            onClick={() => router.back()}
            className="rounded border border-slate-300 bg-white px-4 py-2 font-semibold text-slate-700"
          >
            Retour
          </button>
          <button
            type="button"
            onClick={() => window.print()}
            className="rounded bg-blue-600 px-4 py-2 font-semibold text-white hover:bg-blue-700"
          >
            Imprimer
          </button>
        </div>
      </div>

      <div className="print-pages">
        {report.secteurs.map((secteur, pageIndex) => (
          <section className="print-sheet" key={secteur.id}>
            <div className="report-content">
              <div className="sector-name">{secteur.secteur}</div>

              <div>
                <table className="attendance-table">
                  <colgroup>
                    <col className="name-column" />
                    <col className="firstname-column" />
                    <col className="check-column" />
                    <col className="check-column" />
                    <col className="check-column" />
                  </colgroup>
                  <thead>
                    <tr>
                      <th>Nom</th>
                      <th>Prénom</th>
                      <th>Présent</th>
                      <th>Absent</th>
                      <th>Introuvables</th>
                    </tr>
                  </thead>
                  <tbody>
                    {secteur.salaries.map((salarie) => (
                      <tr key={salarie.cos}>
                        <td>{salarie.nom}</td>
                        <td>{salarie.prenom}</td>
                        <td aria-label="Présent" />
                        <td aria-label="Absent" />
                        <td aria-label="Introuvable" />
                      </tr>
                    ))}
                    {secteur.salaries.length === 0 && (
                      <tr>
                        <td className="empty-sector" colSpan={5}>
                          Aucun salarié actif dans ce secteur
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>

                <div className="totals">
                  <div>Totaux :</div>
                  <div className="total-box" />
                  <div className="total-box" />
                  <div className="total-box" />
                  <div>Solde :</div>
                  <div className="balance-box" />
                  <strong>
                    Nb salariés : {secteur.salaries.length}
                  </strong>
                </div>
              </div>
            </div>

            <p className="visitors-note">
              + Pointer les intérimaires, stagiaires et visiteurs
            </p>

            <footer className="print-footer">
              <span>
                Page {pageIndex + 1} sur {report.secteurs.length + 1}
              </span>
              <span>{formatDate(report.generatedAt)}</span>
            </footer>
          </section>
        ))}

        <section className="print-sheet summary-sheet">
          <div className="summary-content">
            <div className="totals summary-totals">
              <div>Totaux :</div>
              <div className="total-box" />
              <div className="total-box" />
              <div className="total-box" />
              <div>Solde :</div>
              <div className="balance-box" />
              <strong>Nb salariés : {report.totalSalaries}</strong>
            </div>
          </div>

          <footer className="print-footer">
            <span>
              Page {report.secteurs.length + 1} sur{" "}
              {report.secteurs.length + 1}
            </span>
            <span>{formatDate(report.generatedAt)}</span>
          </footer>
        </section>
      </div>

      <style jsx global>{`
        .print-sheet {
          position: relative;
          box-sizing: border-box;
          width: 210mm;
          min-height: 297mm;
          margin: 0 auto 8mm;
          padding: 16mm 14mm 15mm;
          background: white;
          box-shadow: 0 2px 12px rgb(15 23 42 / 15%);
          break-after: page;
          page-break-after: always;
        }

        .print-sheet:last-child {
          break-after: auto;
          page-break-after: auto;
        }

        .report-content {
          display: grid;
          grid-template-columns: 34mm 1fr;
          gap: 5mm;
          align-items: start;
        }

        .sector-name {
          margin-top: 9mm;
          border: 1px solid #111827;
          padding: 1.5mm 2mm;
          font-size: 10pt;
          font-weight: 600;
        }

        .attendance-table {
          width: 100%;
          table-layout: fixed;
          border-collapse: collapse;
          font-size: 9.5pt;
        }

        .attendance-table th {
          height: 9mm;
          border: 0;
          padding: 1mm 1.5mm;
          text-align: left;
          font-weight: 600;
        }

        .attendance-table th:nth-child(n + 3) {
          text-align: center;
        }

        .attendance-table td {
          height: 6mm;
          border: 1px solid #111827;
          padding: 0.6mm 1.3mm;
          line-height: 1.1;
        }

        .attendance-table .empty-sector {
          height: 12mm;
          text-align: center;
          color: #64748b;
          font-style: italic;
        }

        .name-column {
          width: 30%;
        }

        .firstname-column {
          width: 22%;
        }

        .check-column {
          width: 16%;
        }

        .totals {
          display: grid;
          grid-template-columns: 1fr 16% 16% 16%;
          align-items: center;
          gap: 1mm 0;
          margin-top: 1.5mm;
          font-size: 9.5pt;
        }

        .totals > :first-child,
        .totals > :nth-child(5) {
          padding-right: 3mm;
          text-align: right;
        }

        .total-box,
        .balance-box {
          height: 6mm;
          border: 1px solid #111827;
        }

        .balance-box {
          grid-column: 2 / 4;
        }

        .totals strong {
          grid-column: 2 / 5;
          padding-top: 1.5mm;
          text-align: center;
        }

        .summary-content {
          display: flex;
          justify-content: center;
          padding-top: 22mm;
        }

        .summary-totals {
          width: 92mm;
        }

        .visitors-note {
          margin: 15mm 0 0 8mm;
          font-size: 18pt;
        }

        .print-footer {
          position: absolute;
          right: 14mm;
          bottom: 10mm;
          left: 14mm;
          display: flex;
          justify-content: space-between;
          font-size: 9pt;
        }

        @page {
          size: A4 portrait;
          margin: 0;
        }

        @media print {
          html,
          body {
            margin: 0 !important;
            padding: 0 !important;
            background: white !important;
          }

          .screen-toolbar {
            display: none !important;
          }

          .print-report {
            padding: 0 !important;
            background: white !important;
          }

          .print-sheet {
            margin: 0;
            box-shadow: none;
          }
        }
      `}</style>
    </main>
  );
}