"use client";

import React, { useEffect, useState, useCallback, useMemo } from "react";
import { FiSearch, FiBarChart2, FiEyeOff } from "react-icons/fi";
import { AgingFilters } from "./AgingFilters";
import { AgingSummaryCards } from "./AgingSummaryCards";
import { AgingTable } from "./AgingTable";
import {
  fetchAgingReport,
  downloadAgingFile,
  buildFileName,
  type AgingFilters as AgingFiltersType,
  type AgingReport,
} from "./agingApi";

function useDebounce<T>(value: T, delay: number): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const t = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(t);
  }, [value, delay]);
  return debounced;
}

export default function AgingAnalysisModule() {
  const [filters, setFilters] = useState<AgingFiltersType>({
    year: new Date().getFullYear(),
    months: [],
    category: "all",
    source: "Manual",
  });

  const [report, setReport] = useState<AgingReport | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [downloading, setDownloading] = useState<"pdf" | "excel" | null>(null);

  // UI state
  const [showAnalytics, setShowAnalytics] = useState(false); // cards hidden by default
  const [searchTerm, setSearchTerm] = useState("");

  const debouncedFilters = useDebounce(filters, 400);
  const debouncedSearch = useDebounce(searchTerm, 300);

  const load = useCallback(async (f: AgingFiltersType) => {
    setLoading(true);
    setError(null);
    try {
      setReport(await fetchAgingReport(f));
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Failed to load report");
      setReport(null);
    } finally {
      setLoading(false);
    }
  }, []);

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

  const handleDownload = async (kind: "pdf" | "excel") => {
    setDownloading(kind);
    try {
      await downloadAgingFile(kind, filters, buildFileName(kind, filters, report));
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : "Download failed");
    } finally {
      setDownloading(null);
    }
  };

  // Client-side search over rows
  const filteredRows = useMemo(() => {
    if (!report) return [];
    const q = debouncedSearch.trim().toLowerCase();
    if (!q) return report.rows;
    return report.rows.filter(
      (r) =>
        r.certificate_no?.toLowerCase().includes(q) ||
        r.company_name?.toLowerCase().includes(q) ||
        r.standard?.toLowerCase().includes(q) ||
        r.status?.toLowerCase().includes(q),
    );
  }, [report, debouncedSearch]);

  const hasRows = !!report && report.summary.total > 0;

  return (
    <div style={{ padding: "0 4px" }}>
      {/* Header */}
      <div
        style={{
          background: "linear-gradient(135deg, #4A0080 0%, #8B14D4 100%)",
          borderRadius: 14,
          padding: "20px 24px",
          marginBottom: 16,
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
          flexWrap: "wrap",
          gap: 12,
          boxShadow: "0 4px 18px rgba(74,0,128,0.25)",
        }}
      >
        <div>
          <h1 style={{ margin: 0, color: "#fff", fontSize: 24, fontWeight: 800, letterSpacing: -0.3 }}>
            Aging Analysis Report
          </h1>
          <p style={{ margin: "4px 0 0", color: "rgba(255,255,255,0.82)", fontSize: 13 }}>
            Certification lifecycle by original registration — Re-certification &amp;
            Surveillance cycle (Manual + QRS &amp; TQS)
          </p>
        </div>

        <div style={{ display: "flex", gap: 10 }}>
          <button
            onClick={() => handleDownload("excel")}
            disabled={!hasRows || downloading !== null}
            style={exportBtn("linear-gradient(135deg, #166534 0%, #22c55e 100%)", !hasRows || !!downloading)}
          >
            {downloading === "excel" ? "Preparing…" : "⬇ Excel"}
          </button>
          <button
            onClick={() => handleDownload("pdf")}
            disabled={!hasRows || downloading !== null}
            style={exportBtn("linear-gradient(135deg, #b91c1c 0%, #ef4444 100%)", !hasRows || !!downloading)}
          >
            {downloading === "pdf" ? "Preparing…" : "⬇ PDF"}
          </button>
        </div>
      </div>

      {/* Toolbar: search + Analytics toggle */}
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap", marginBottom: 14 }}>
        <div
          style={{
            flex: 1,
            minWidth: 260,
            display: "flex",
            alignItems: "center",
            gap: 8,
            padding: "9px 14px",
            background: "#fff",
            border: "1px solid #e2e8f0",
            borderRadius: 10,
          }}
        >
          <FiSearch size={16} color="#94a3b8" />
          <input
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            placeholder="Search by cert no, company, standard, status…"
            style={{ border: "none", outline: "none", flex: 1, fontSize: 14, background: "transparent" }}
          />
          {searchTerm && (
            <button
              onClick={() => setSearchTerm("")}
              style={{ border: "none", background: "none", color: "#94a3b8", cursor: "pointer", fontSize: 16 }}
            >
              ✕
            </button>
          )}
        </div>

        <button
          onClick={() => setShowAnalytics((p) => !p)}
          style={{
            display: "inline-flex",
            alignItems: "center",
            gap: 6,
            padding: "10px 18px",
            background: showAnalytics
              ? "linear-gradient(135deg, #10b981 0%, #059669 100%)"
              : "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
            color: "#fff",
            border: "none",
            borderRadius: 10,
            fontSize: 14,
            fontWeight: 700,
            cursor: "pointer",
            boxShadow: showAnalytics ? "0 2px 8px rgba(16,185,129,0.3)" : "0 2px 8px rgba(102,126,234,0.3)",
            whiteSpace: "nowrap",
          }}
        >
          {showAnalytics ? <><FiEyeOff size={16} /> Hide Analytics</> : <><FiBarChart2 size={16} /> Analytics</>}
        </button>
      </div>

      {/* Filters */}
      <AgingFilters filters={filters} setFilters={setFilters} onRefresh={() => load(filters)} />

      {/* Due-for-period banner */}
      <div
        style={{
          padding: "10px 16px",
          background: "#faf5ff",
          border: "1px solid #e9d5ff",
          borderRadius: 8,
          marginBottom: 12,
          fontSize: 13,
          color: "#6b21a8",
        }}
      >
        {loading
          ? "Loading report…"
          : report
            ? <>📊 <strong>{report.summary.total.toLocaleString()}</strong> certificate(s) due for {report.meta.period_label}</>
            : "No data"}
      </div>

      {/* Analytics (cards) — collapsible */}
      {showAnalytics && report && hasRows && <AgingSummaryCards report={report} />}

      {/* Body */}
      {error ? (
        <div style={{ padding: 24, textAlign: "center", background: "#fef2f2", border: "1px solid #fecaca", borderRadius: 12, color: "#b91c1c" }}>
          <div style={{ fontSize: 28, marginBottom: 8 }}>⚠️</div>
          <div style={{ fontWeight: 700, marginBottom: 4 }}>Error</div>
          <div style={{ fontSize: 13 }}>{error}</div>
          <button
            onClick={() => load(filters)}
            style={{ marginTop: 12, padding: "8px 16px", borderRadius: 8, border: "none", background: "#b91c1c", color: "#fff", fontWeight: 600, cursor: "pointer" }}
          >
            Retry
          </button>
        </div>
      ) : loading && !report ? (
        <div style={{ textAlign: "center", padding: 60, color: "#9ca3af" }}>
          <div
            style={{
              display: "inline-block", width: 28, height: 28,
              border: "3px solid #e9d5ff", borderTopColor: "#8B14D4",
              borderRadius: "50%", animation: "spin 0.7s linear infinite", marginBottom: 10,
            }}
          />
          <p style={{ margin: 0 }}>Loading…</p>
          <style>{`@keyframes spin{to{transform:rotate(360deg)}}`}</style>
        </div>
      ) : report && hasRows ? (
        <AgingTable rows={filteredRows} />
      ) : (
        <div style={{ textAlign: "center", padding: 60 }}>
          <div style={{ fontSize: 36, marginBottom: 8 }}>📭</div>
          <h3 style={{ margin: 0, color: "#111827" }}>No certificates due</h3>
          <p style={{ color: "#6b7280", margin: "6px 0 0", fontSize: 13 }}>
            Nothing matches these filters. Try a different year, months, or category.
          </p>
        </div>
      )}
    </div>
  );
}

function exportBtn(gradient: string, disabled: boolean): React.CSSProperties {
  return {
    display: "inline-flex",
    alignItems: "center",
    gap: 6,
    padding: "10px 18px",
    background: gradient,
    color: "#fff",
    border: "none",
    borderRadius: 8,
    fontSize: 13,
    fontWeight: 700,
    cursor: disabled ? "not-allowed" : "pointer",
    opacity: disabled ? 0.6 : 1,
  };
}
