"use client";

import React, { useEffect, useState, useMemo } from "react";
import { useRouter } from "next/navigation";
import { getTemplatesPaginated } from "@/lib/api/template.api";
import { mapTemplatesApiResponse } from "@/lib/api/mappers/template.mappers";
import type { TemplateRow } from "@/lib/api/types/template.types";
import { FiArrowLeft, FiDownload } from "react-icons/fi";
import { FcPrint } from "react-icons/fc";

// ─── Constants ────────────────────────────────────────────────────────────────
const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

const STAGE_COLORS: Record<string, { bg: string; text: string; bar: string }> = {
  "Stage 1": { bg: "#dbeafe", text: "#1d4ed8", bar: "#2563eb" },
  "Stage 2": { bg: "#ede9fe", text: "#6d28d9", bar: "#7c3aed" },
};

const TYPE_COLORS: Record<string, { bg: string; text: string; bar: string }> = {
  DOCUMENT:    { bg: "#f1f5f9", text: "#475569", bar: "#64748b" },
  CERTIFICATE: { bg: "#dcfce7", text: "#15803d", bar: "#16a34a" },
};

// ─── Sub-components ───────────────────────────────────────────────────────────
function KpiCard({ label, value, color, bg }: { label: string; value: string | number; color: string; bg: string }) {
  return (
    <div style={{ padding: "20px 24px", borderRadius: "12px", backgroundColor: bg, border: `1px solid ${color}22`, flex: 1, minWidth: 0 }}>
      <div style={{ fontSize: "28px", fontWeight: 800, color }}>{value}</div>
      <div style={{ fontSize: "12px", color: "#6b7280", marginTop: "4px", fontWeight: 500 }}>{label}</div>
    </div>
  );
}

function BarRow({ label, count, max, color }: { label: string; count: number; max: number; color: string }) {
  return (
    <div style={{ marginBottom: "12px" }}>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: "12px", marginBottom: "4px" }}>
        <span style={{ color: "#374151", fontWeight: 500 }}>{label}</span>
        <span style={{ color, fontWeight: 700 }}>{count}</span>
      </div>
      <div style={{ height: "6px", borderRadius: "3px", backgroundColor: "#f3f4f6", overflow: "hidden" }}>
        <div style={{ height: "100%", borderRadius: "3px", backgroundColor: color, width: `${max > 0 ? (count / max) * 100 : 0}%`, transition: "width 0.5s ease" }} />
      </div>
    </div>
  );
}

// ─── Main page ────────────────────────────────────────────────────────────────
export default function TemplateReportPage() {
  const router = useRouter();
  const [templates, setTemplates] = useState<TemplateRow[]>([]);
  const [loading, setLoading]     = useState(true);
  const [error, setError]         = useState<string | null>(null);

  // Filters
  const [yearFilter,  setYearFilter]  = useState(new Date().getFullYear());
  const [monthFilter, setMonthFilter] = useState<string>("all");
  const [stageFilter, setStageFilter] = useState<string>("all");
  const [typeFilter,  setTypeFilter]  = useState<string>("all");

  // ── Load all templates ────────────────────────────────────────────────────
  useEffect(() => {
    setLoading(true);
    getTemplatesPaginated(1, 500)
      .then((res) => setTemplates(mapTemplatesApiResponse(res.data)))
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false));
  }, []);

  // ── Derived data ──────────────────────────────────────────────────────────
  const filtered = useMemo(() => {
    return templates.filter((t) => {
      const d = t.createdAt ? new Date(t.createdAt) : null;
      if (d && d.getFullYear() !== yearFilter) return false;
      if (monthFilter !== "all" && d && MONTHS[d.getMonth()] !== monthFilter) return false;
      if (stageFilter !== "all" && t.stageName    !== stageFilter) return false;
      if (typeFilter  !== "all" && t.templateType !== typeFilter)  return false;
      return true;
    });
  }, [templates, yearFilter, monthFilter, stageFilter, typeFilter]);

  const total      = filtered.length;
  const byStage    = ["Stage 1", "Stage 2"].map((name) => ({ name, count: filtered.filter((t) => t.stageName === name).length }));
  const byType     = ["DOCUMENT", "CERTIFICATE"].map((name) => ({ name, count: filtered.filter((t) => t.templateType === name).length }));
  const activeCount = filtered.filter((t) => t.isActive).length;

  const byMonth = useMemo(() => {
    const map: Record<string, number> = {};
    MONTHS.forEach((m) => (map[m] = 0));
    filtered.forEach((t) => { if (t.createdAt) { const m = MONTHS[new Date(t.createdAt).getMonth()]; map[m] = (map[m] ?? 0) + 1; } });
    return MONTHS.map((m) => ({ month: m, count: map[m] ?? 0 }));
  }, [filtered]);
  const maxMonth = Math.max(...byMonth.map((b) => b.count), 1);

  // ── Render ────────────────────────────────────────────────────────────────
  if (error) return (
    <div style={{ padding: 40, textAlign: "center" }}>
      <p style={{ color: "#ef4444" }}>{error}</p>
      <button onClick={() => window.location.reload()} style={{ marginTop: 12, padding: "8px 20px", borderRadius: 8, background: "#0f766e", color: "#fff", border: "none", cursor: "pointer" }}>Retry</button>
    </div>
  );

  return (
    <div style={{ padding: "28px 32px", maxWidth: "1200px", margin: "0 auto", fontFamily: "system-ui,sans-serif" }}>

      {/* ── Page Header ──────────────────────────────────────────────────── */}
      <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", marginBottom: "24px" }}>
        <div>
          <button
            onClick={() => router.push("/modules/templates")}
            style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 13, color: "#6b7280", background: "none", border: "none", cursor: "pointer", marginBottom: 8, padding: 0 }}
          >
            <FiArrowLeft size={14} /> Back to Templates
          </button>
          <h1 style={{ margin: 0, fontSize: "22px", fontWeight: 800, color: "#111827" }}>📊 Template Reports</h1>
          <p style={{ margin: "4px 0 0", fontSize: "13px", color: "#6b7280" }}>
            Overview of all registered PDF templates and certificates
          </p>
        </div>
        <div style={{ display: "flex", gap: 8 }}>
          <button
            onClick={() => window.print()}
            style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 14px", borderRadius: 8, border: "1px solid #e5e7eb", background: "#fff", color: "#374151", fontSize: 13, fontWeight: 600, cursor: "pointer" }}
          >
            <FcPrint size={16} /> Print
          </button>
          <button
            style={{ display: "flex", alignItems: "center", gap: 6, padding: "8px 14px", borderRadius: 8, border: "none", background: "linear-gradient(135deg,#0f766e,#14b8a6)", color: "#fff", fontSize: 13, fontWeight: 600, cursor: "pointer" }}
          >
            <FiDownload size={14} /> Export Excel
          </button>
        </div>
      </div>

      {/* ── Filters ──────────────────────────────────────────────────────── */}
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginBottom: "24px", padding: "16px 20px", backgroundColor: "#f8fafc", borderRadius: "12px", border: "1px solid #e5e7eb" }}>
        {[
          { label: "Year",  value: yearFilter,  onChange: (v: string) => setYearFilter(Number(v)), options: [{ v: 2024, l: "2024" }, { v: 2025, l: "2025" }, { v: 2026, l: "2026" }] },
          { label: "Month", value: monthFilter, onChange: (v: string) => setMonthFilter(v), options: [{ v: "all", l: "All Months" }, ...MONTHS.map((m) => ({ v: m, l: m }))] },
          { label: "Stage", value: stageFilter, onChange: (v: string) => setStageFilter(v), options: [{ v: "all", l: "All Stages" }, { v: "Stage 1", l: "Stage 1" }, { v: "Stage 2", l: "Stage 2" }] },
          { label: "Type",  value: typeFilter,  onChange: (v: string) => setTypeFilter(v),  options: [{ v: "all", l: "All Types" }, { v: "DOCUMENT", l: "DOCUMENT" }, { v: "CERTIFICATE", l: "CERTIFICATE" }] },
        ].map((f) => (
          <div key={f.label}>
            <label style={{ display: "block", fontSize: 11, fontWeight: 600, color: "#6b7280", marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.05em" }}>{f.label}</label>
            <select value={f.value} onChange={(e) => f.onChange(e.target.value)} style={{ padding: "7px 10px", borderRadius: 8, border: "1px solid #e5e7eb", fontSize: 13, color: "#374151", background: "#fff" }}>
              {f.options.map((o) => <option key={o.v} value={o.v}>{o.l}</option>)}
            </select>
          </div>
        ))}
        <div style={{ alignSelf: "flex-end" }}>
          <button
            onClick={() => { setYearFilter(new Date().getFullYear()); setMonthFilter("all"); setStageFilter("all"); setTypeFilter("all"); }}
            style={{ padding: "7px 14px", borderRadius: 8, border: "1px solid #e5e7eb", background: "#fff", fontSize: 13, color: "#6b7280", cursor: "pointer" }}
          >
            ✕ Clear
          </button>
        </div>
      </div>

      {loading ? (
        <div style={{ textAlign: "center", padding: "80px", color: "#9ca3af" }}>
          <div style={{ fontSize: 32, marginBottom: 12 }}>⏳</div>
          Loading report data...
        </div>
      ) : (
        <>
          {/* ── KPI Cards ──────────────────────────────────────────────── */}
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginBottom: "24px" }}>
            <KpiCard label="Total Templates"  value={total}        color="#0f766e" bg="#f0fdfa" />
            <KpiCard label="Stage 1"          value={byStage[0].count} color="#2563eb" bg="#eff6ff" />
            <KpiCard label="Stage 2"          value={byStage[1].count} color="#7c3aed" bg="#f5f3ff" />
            <KpiCard label="Documents"        value={byType[0].count}  color="#475569" bg="#f8fafc" />
            <KpiCard label="Certificates"     value={byType[1].count}  color="#15803d" bg="#f0fdf4" />
            <KpiCard label="Active"           value={activeCount}  color="#0f766e" bg="#f0fdfa" />
          </div>

          {/* ── Middle Row: Stage + Type ────────────────────────────────── */}
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px", marginBottom: "20px" }}>
            <div style={{ background: "#fff", border: "1px solid #e5e7eb", borderRadius: "14px", padding: "20px" }}>
              <h3 style={{ margin: "0 0 16px", fontSize: "14px", fontWeight: 700, color: "#111827" }}>Stage Distribution</h3>
              {byStage.map((s) => <BarRow key={s.name} label={s.name} count={s.count} max={total || 1} color={STAGE_COLORS[s.name]?.bar ?? "#6b7280"} />)}
            </div>
            <div style={{ background: "#fff", border: "1px solid #e5e7eb", borderRadius: "14px", padding: "20px" }}>
              <h3 style={{ margin: "0 0 16px", fontSize: "14px", fontWeight: 700, color: "#111827" }}>Type Distribution</h3>
              {byType.map((t) => <BarRow key={t.name} label={t.name} count={t.count} max={total || 1} color={TYPE_COLORS[t.name]?.bar ?? "#6b7280"} />)}
            </div>
          </div>

          {/* ── Monthly Chart ───────────────────────────────────────────── */}
          <div style={{ background: "#fff", border: "1px solid #e5e7eb", borderRadius: "14px", padding: "20px", marginBottom: "20px" }}>
            <h3 style={{ margin: "0 0 16px", fontSize: "14px", fontWeight: 700, color: "#111827" }}>Monthly Additions — {yearFilter}</h3>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(12,1fr)", gap: 6, alignItems: "flex-end", height: 120 }}>
              {byMonth.map((b) => (
                <div key={b.month} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 4, height: "100%" }}>
                  <div style={{ flex: 1, display: "flex", alignItems: "flex-end", width: "100%" }}>
                    <div style={{ width: "100%", backgroundColor: b.count > 0 ? "#14b8a6" : "#f0fdfa", borderRadius: "4px 4px 0 0", height: `${maxMonth > 0 ? (b.count / maxMonth) * 100 : 0}%`, minHeight: b.count > 0 ? 4 : 0, transition: "height 0.4s ease", position: "relative" }} title={`${b.month}: ${b.count}`}>
                      {b.count > 0 && <span style={{ position: "absolute", top: -18, left: "50%", transform: "translateX(-50%)", fontSize: 10, color: "#0f766e", fontWeight: 700, whiteSpace: "nowrap" }}>{b.count}</span>}
                    </div>
                  </div>
                  <span style={{ fontSize: 9, color: "#9ca3af", fontWeight: 500 }}>{b.month}</span>
                </div>
              ))}
            </div>
          </div>

          {/* ── Templates Table ─────────────────────────────────────────── */}
          <div style={{ background: "#fff", border: "1px solid #e5e7eb", borderRadius: "14px", overflow: "hidden" }}>
            <div style={{ padding: "16px 20px", borderBottom: "1px solid #f3f4f6", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <h3 style={{ margin: 0, fontSize: "14px", fontWeight: 700, color: "#111827" }}>
                Template List
                <span style={{ marginLeft: 8, padding: "2px 8px", borderRadius: 20, backgroundColor: "#f0fdfa", color: "#0f766e", fontSize: 11, fontWeight: 700 }}>{filtered.length}</span>
              </h3>
            </div>
            <div style={{ overflowX: "auto" }}>
              <table style={{ width: "100%", borderCollapse: "collapse", fontSize: "12px" }}>
                <thead>
                  <tr style={{ backgroundColor: "#f9fafb" }}>
                    {["#", "ID", "Name", "Stage", "Type", "Version", "Status", "Created"].map((h) => (
                      <th key={h} style={{ padding: "10px 14px", textAlign: "left", fontWeight: 700, color: "#6b7280", fontSize: "11px", textTransform: "uppercase", letterSpacing: "0.04em", whiteSpace: "nowrap" }}>{h}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {filtered.slice(0, 100).map((t, i) => {
                    const stageC = STAGE_COLORS[t.stageName];
                    const typeC  = TYPE_COLORS[t.templateType];
                    return (
                      <tr key={t.id} style={{ borderBottom: "1px solid #f3f4f6" }}>
                        <td style={{ padding: "10px 14px", color: "#9ca3af", fontWeight: 600 }}>{i + 1}</td>
                        <td style={{ padding: "10px 14px", fontFamily: "monospace", fontSize: "11px", color: "#6b7280" }}>#{t.id}</td>
                        <td style={{ padding: "10px 14px", fontWeight: 600, color: "#111827", maxWidth: 280 }}>
                          <div style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{t.name}</div>
                        </td>
                        <td style={{ padding: "10px 14px" }}>
                          <span style={{ padding: "2px 8px", borderRadius: 10, fontSize: 10, fontWeight: 600, backgroundColor: stageC?.bg ?? "#f3f4f6", color: stageC?.text ?? "#374151" }}>{t.stageName}</span>
                        </td>
                        <td style={{ padding: "10px 14px" }}>
                          <span style={{ padding: "2px 8px", borderRadius: 10, fontSize: 10, fontWeight: 600, backgroundColor: typeC?.bg ?? "#f3f4f6", color: typeC?.text ?? "#374151" }}>{t.templateType}</span>
                        </td>
                        <td style={{ padding: "10px 14px", fontFamily: "monospace", fontSize: "11px", color: "#64748b" }}>{t.version}</td>
                        <td style={{ padding: "10px 14px" }}>
                          <span style={{ padding: "2px 8px", borderRadius: 10, fontSize: 10, fontWeight: 600, backgroundColor: t.isActive ? "#d1fae5" : "#f3f4f6", color: t.isActive ? "#065f46" : "#6b7280" }}>
                            {t.isActive ? "Active" : "Inactive"}
                          </span>
                        </td>
                        <td style={{ padding: "10px 14px", color: "#6b7280", whiteSpace: "nowrap" }}>
                          {t.createdAt ? new Date(t.createdAt).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" }).replace(/ /g, "-") : "—"}
                        </td>
                      </tr>
                    );
                  })}
                  {filtered.length > 100 && (
                    <tr><td colSpan={8} style={{ padding: "12px 14px", textAlign: "center", color: "#9ca3af", fontSize: 12 }}>Showing 100 of {filtered.length} — export for full list</td></tr>
                  )}
                  {filtered.length === 0 && (
                    <tr><td colSpan={8} style={{ padding: "40px", textAlign: "center", color: "#9ca3af" }}>No templates match the selected filters</td></tr>
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
