"use client";

import React, { useCallback, useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import { FiArrowLeft, FiRefreshCw, FiDownload, FiArrowRight, FiEye, FiFileText } from "react-icons/fi";
import { FaSearchLocation } from "react-icons/fa";
import styles from "../commonstyle/dattabale.module.css";
import { EnterpriseLoader } from "../../../../components/loader/loader";
import { Pagination } from "../companies/Pagination";
import { listReports, openReportPdf } from "@/lib/api/audit-report-builder.api";
import type {
  ReportListItem,
  ReportListResponse,
  ReportStatus,
  StageType,
} from "@/lib/api/types/audit-report-builder.types";
import {
  REPORT_STATUS_CONFIG,
  STAGE_CONFIG,
  fmtDate,
} from "@/lib/api/mappers/audit-report-builder.mappers";
import DigitalReportModal from "./DigitalReportModal";

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

const STATUS_OPTIONS: { value: ReportStatus | "all"; label: string }[] = [
  { value: "all", label: "All Statuses" },
  { value: "draft", label: "Draft" },
  { value: "submitted", label: "Submitted (awaiting approval)" },
  { value: "returned", label: "Returned" },
  { value: "approved", label: "Approved" },
  { value: "locked", label: "Locked" },
];

const STAGE_OPTIONS: { value: StageType | "all"; label: string }[] = [
  { value: "all", label: "All Stages" },
  { value: "stage1", label: "Stage 1" },
  { value: "stage2", label: "Stage 2" },
  { value: "surveillance", label: "Surveillance" },
  { value: "recert", label: "Re-Certification" },
];

const thStyle: React.CSSProperties = {
  padding: "10px",
  textAlign: "left",
  fontSize: 10,
  fontWeight: 700,
  color: "#6b7280",
  textTransform: "uppercase",
  letterSpacing: "0.05em",
};

const selectStyle = (active: boolean, color: string, bg: string): React.CSSProperties => ({
  minWidth: 150,
  padding: "7px 12px",
  borderRadius: 8,
  border: active ? `1.5px solid ${color}` : "1px solid #cbd5e1",
  background: active ? bg : "#fff",
  fontSize: 13,
  fontWeight: 600,
  color: active ? color : "#475569",
  cursor: "pointer",
  outline: "none",
});

export default function MyAuditReportsPage() {
  const router = useRouter();

  const [res, setRes] = useState<ReportListResponse | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage, setItemsPerPage] = useState(10);
  const [searchTerm, setSearchTerm] = useState("");
  const [statusFilter, setStatusFilter] = useState<ReportStatus | "all">("all");
  const [stageFilter, setStageFilter] = useState<StageType | "all">("all");
  const debouncedSearch = useDebounce(searchTerm, 400);
  // 2026-11-10: "Digital Report" popup (Word + PDF download) for the Audit Report column
  const [digital, setDigital] = useState<ReportListItem | null>(null);

  const fetchPage = useCallback(() => {
    setLoading(true);
    listReports({
      page: currentPage,
      limit: itemsPerPage,
      search: debouncedSearch || undefined,
      status: statusFilter,
      stage_type: stageFilter,
    })
      .then((r) => {
        setRes(r);
        setError(null);
      })
      .catch((e) => setError(e.message))
      .finally(() => setLoading(false));
  }, [currentPage, itemsPerPage, debouncedSearch, statusFilter, stageFilter]);

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

  // any filter change → back to page 1
  useEffect(() => {
    setCurrentPage(1);
  }, [debouncedSearch, statusFilter, stageFilter]);

  const clearFilters = () => {
    setSearchTerm("");
    setStatusFilter("all");
    setStageFilter("all");
  };

  const openReport = (r: ReportListItem) =>
    router.push(`/modules/audits/${r.audit_schedule_row_id}/report/${r.id}`);

  const rows = res?.rows ?? [];
  const total = res?.total ?? 0;
  const hasFilters = !!(searchTerm || statusFilter !== "all" || stageFilter !== "all");

  if (error && !res)
    return (
      <div className={styles.errorContainer}>
        <div className={styles.errorIcon}>⚠️</div>
        <h3 className={styles.errorTitle}>Error</h3>
        <p className={styles.errorMessage}>{error}</p>
        <button className={styles.errorButton} onClick={fetchPage}>
          Retry
        </button>
      </div>
    );

  return (
    <div className={styles.container}>
      {/* Header (same gradient header as My Audits) */}
      <div className={styles.header}>
        <div className={styles.headerLeft}>
          <h1 className={styles.title}>My Audit Reports</h1>
          <p className={styles.subtitle}>
            Form 04-2a reports for your audits
            {total > 0 ? ` · ${total.toLocaleString()} total` : ""}
          </p>
        </div>
        <div className={styles.headerRight}>
          <button
            onClick={() => router.push("/modules/my-audits")}
            style={{
              background: "rgba(255,255,255,0.15)",
              color: "#fff",
              border: "1px solid rgba(255,255,255,0.3)",
              display: "inline-flex",
              alignItems: "center",
              gap: 6,
              padding: "8px 16px",
              borderRadius: 8,
              fontSize: "0.875rem",
              fontWeight: 600,
              cursor: "pointer",
              marginRight: 8,
            }}
          >
            <FiArrowLeft size={14} /> My Audits
          </button>
          <button
            className={styles.btnSecondary}
            onClick={fetchPage}
            title="Refresh"
            style={{
              background: "rgba(255,255,255,0.15)",
              color: "#fff",
              border: "1px solid rgba(255,255,255,0.3)",
              display: "inline-flex",
              alignItems: "center",
              gap: 6,
            }}
          >
            <FiRefreshCw size={14} /> Refresh
          </button>
        </div>
      </div>

      {/* Toolbar */}
      <div className={styles.toolbar}>
        <div className={styles.toolbarTop}>
          <div className={styles.searchBox}>
            <span className={styles.searchIcon}>
              <FaSearchLocation />
            </span>
            <input
              type="text"
              aria-label="Search reports"
              placeholder="Search by report no. or company..."
              className={styles.searchInput}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
          <div className={styles.toolbarActions}>
            <button className={styles.btnIcon} title="Refresh" onClick={fetchPage}>
              <FiRefreshCw size={16} />
            </button>
          </div>
        </div>

        <div
          className={styles.toolbarFilters}
          style={{
            display: "flex",
            flexWrap: "wrap",
            alignItems: "center",
            gap: 10,
            padding: "12px 14px",
            background: "#f8fafc",
            border: "1px solid #e2e8f0",
            borderRadius: 10,
          }}
        >
          <span
            style={{
              fontSize: 11,
              fontWeight: 700,
              color: "#64748b",
              textTransform: "uppercase",
              letterSpacing: "0.05em",
              marginRight: 4,
            }}
          >
            🔍 Filters:
          </span>
          <select
            className={styles.filterSelect}
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value as ReportStatus | "all")}
            style={selectStyle(statusFilter !== "all", "#0f766e", "#f0fdfa")}
          >
            {STATUS_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
          <select
            className={styles.filterSelect}
            value={stageFilter}
            onChange={(e) => setStageFilter(e.target.value as StageType | "all")}
            style={selectStyle(stageFilter !== "all", "#d97706", "#fffbeb")}
          >
            {STAGE_OPTIONS.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
          {hasFilters && (
            <button
              onClick={clearFilters}
              style={{
                padding: "7px 12px",
                borderRadius: 8,
                border: "1px solid #fca5a5",
                background: "#fef2f2",
                color: "#b91c1c",
                fontSize: 12,
                fontWeight: 600,
                cursor: "pointer",
              }}
            >
              ✕ Clear
            </button>
          )}
        </div>
      </div>

      {res && total > 0 && (
        <div
          style={{
            padding: "10px 16px",
            backgroundColor: "#f0fdfa",
            border: "1px solid #99f6e4",
            borderRadius: 8,
            marginBottom: 12,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            fontSize: 13,
            color: "#0f766e",
          }}
        >
          <span>
            📋 Showing{" "}
            <strong>
              {(currentPage - 1) * itemsPerPage + 1}–{Math.min(currentPage * itemsPerPage, total)}
            </strong>{" "}
            of <strong>{total.toLocaleString()}</strong> reports
          </span>
        </div>
      )}

      <div className={styles.tableWrapper}>
        <table className={styles.table} style={{ tableLayout: "fixed", width: "100%" }}>
          <colgroup>
            <col style={{ width: 170 }} />
            <col style={{ width: 240 }} />
            <col style={{ width: 130 }} />
            <col style={{ width: 120 }} />
            <col style={{ width: 130 }} />
            <col style={{ width: 130 }} />
            <col style={{ width: 150 }} />
            <col style={{ width: 170 }} />
          </colgroup>
          <thead>
            <tr style={{ background: "#f8fafc" }}>
              <th style={thStyle}>Report No.</th>
              <th style={thStyle}>Client</th>
              <th style={thStyle}>Stage</th>
              <th style={thStyle}>Status</th>
              <th style={thStyle}>Submitted</th>
              <th style={thStyle}>Updated</th>
              <th style={thStyle}>Audit Report</th>
              <th style={thStyle}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td colSpan={8} style={{ textAlign: "center", padding: "60px" }}>
                  <EnterpriseLoader />
                </td>
              </tr>
            ) : rows.length === 0 ? (
              <tr>
                <td colSpan={8} style={{ textAlign: "center", padding: "60px" }}>
                  <div style={{ fontSize: 36 }}>📄</div>
                  <h3 style={{ margin: "12px 0 4px", color: "#111827" }}>No reports found</h3>
                  <p style={{ color: "#6b7280", margin: 0 }}>
                    {hasFilters
                      ? "No reports match your filters."
                      : "Create a report from an audit's Report tab."}
                  </p>
                </td>
              </tr>
            ) : (
              rows.map((r) => {
                const st = REPORT_STATUS_CONFIG[r.status];
                const sg = STAGE_CONFIG[r.stage_type];
                const editable = r.status === "draft" || r.status === "returned";
                const final = r.status === "approved" || r.status === "locked";
                return (
                  <tr key={r.id} style={{ borderTop: "1px solid #f1f5f9" }}>
                    <td style={{ padding: "12px 10px", verticalAlign: "top" }}>
                      <a
                        href={`/modules/audits/${r.audit_schedule_row_id}/report/${r.id}`}
                        onClick={(e) => {
                          e.preventDefault();
                          openReport(r);
                        }}
                        style={{
                          fontFamily: "'JetBrains Mono', monospace",
                          fontSize: 11,
                          color: "#4f46e5",
                          fontWeight: 600,
                          textDecoration: "underline dotted",
                          textDecorationThickness: "1.5px",
                          textUnderlineOffset: "4px",
                          whiteSpace: "nowrap",
                          cursor: "pointer",
                        }}
                      >
                        {r.report_no ?? `#${r.id}`}
                      </a>
                      <div style={{ fontSize: 10, color: "#9ca3af", marginTop: 4 }}>
                        v{r.version} · audit #{r.audit_schedule_row_id}
                      </div>
                    </td>
                    <td style={{ padding: "12px 10px", verticalAlign: "top" }}>
                      <div
                        style={{
                          fontWeight: 600,
                          fontSize: 13,
                          color: "#111827",
                          overflow: "hidden",
                          textOverflow: "ellipsis",
                          whiteSpace: "nowrap",
                        }}
                        title={r.company_name ?? ""}
                      >
                        {r.company_name ?? "—"}
                      </div>
                    </td>
                    <td style={{ padding: "12px 10px", verticalAlign: "top" }}>
                      <span
                        style={{
                          padding: "2px 8px",
                          borderRadius: 99,
                          background: sg.bg,
                          color: sg.color,
                          fontSize: 10,
                          fontWeight: 600,
                          whiteSpace: "nowrap",
                        }}
                      >
                        {sg.label}
                      </span>
                      {r.standard_id === 0 && (
                        <span style={{ marginLeft: 6, padding: "2px 8px", borderRadius: 99, background: "#ede9fe", color: "#5b21b6", fontSize: 10, fontWeight: 700 }}>
                          COMBINED
                        </span>
                      )}
                    </td>
                    <td style={{ padding: "12px 10px", verticalAlign: "top" }}>
                      <span
                        style={{
                          display: "inline-flex",
                          alignItems: "center",
                          gap: 5,
                          padding: "3px 10px",
                          borderRadius: 99,
                          background: st.bg,
                          color: st.text,
                          fontSize: 11,
                          fontWeight: 700,
                          whiteSpace: "nowrap",
                        }}
                      >
                        <span style={{ width: 6, height: 6, borderRadius: "50%", background: st.dot }} />
                        {st.label}
                      </span>
                    </td>
                    <td style={{ padding: "12px 10px", verticalAlign: "top", fontSize: 12, color: "#374151" }}>
                      {fmtDate(r.submitted_at)}
                    </td>
                    <td style={{ padding: "12px 10px", verticalAlign: "top", fontSize: 12, color: "#374151" }}>
                      {fmtDate(r.updated_at)}
                    </td>
                    <td style={{ padding: "12px 10px", verticalAlign: "top" }}>
                      {final && !!r.has_pdf ? (
                        <button
                          onClick={() => setDigital(r)}
                          title="Download the generated report as Word or PDF"
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 5,
                            padding: "5px 10px",
                            borderRadius: 6,
                            border: "1px solid #5eead4",
                            background: "linear-gradient(135deg,#f0fdfa,#ccfbf1)",
                            color: "#0f766e",
                            fontSize: 11,
                            fontWeight: 700,
                            cursor: "pointer",
                            whiteSpace: "nowrap",
                          }}
                        >
                          <FiFileText size={12} /> Digital Report
                        </button>
                      ) : (
                        <span style={{ fontSize: 11, color: "#94a3b8" }} title="Available once the report is approved and generated">
                          Not generated yet
                        </span>
                      )}
                    </td>
                    <td style={{ padding: "12px 10px", verticalAlign: "top" }}>
                      <div style={{ display: "flex", gap: 6 }}>
                        <button
                          onClick={() => openReport(r)}
                          style={{
                            display: "inline-flex",
                            alignItems: "center",
                            gap: 4,
                            padding: "5px 10px",
                            borderRadius: 6,
                            border: "1px solid #c7d2fe",
                            background: "#eef2ff",
                            color: "#4338ca",
                            fontSize: 11,
                            fontWeight: 600,
                            cursor: "pointer",
                            whiteSpace: "nowrap",
                          }}
                        >
                          {editable ? (
                            <>
                              <FiArrowRight size={12} /> Edit
                            </>
                          ) : (
                            <>
                              <FiEye size={12} /> View
                            </>
                          )}
                        </button>
                        {final && !!r.has_pdf && (
                          <button
                            onClick={() => openReportPdf(r.id).catch((e) => toast.error(e.message))}
                            title="Open final PDF"
                            style={{
                              display: "inline-flex",
                              alignItems: "center",
                              gap: 4,
                              padding: "5px 9px",
                              borderRadius: 6,
                              border: "1px solid #86efac",
                              background: "#f0fdf4",
                              color: "#166534",
                              fontSize: 11,
                              fontWeight: 600,
                              cursor: "pointer",
                            }}
                          >
                            <FiDownload size={12} />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                );
              })
            )}
          </tbody>
        </table>
      </div>

      <DigitalReportModal report={digital} onClose={() => setDigital(null)} />

      {res && (
        <Pagination
          currentPage={currentPage}
          setCurrentPage={setCurrentPage}
          totalPages={res.totalPages}
          startIndex={(currentPage - 1) * itemsPerPage + 1}
          endIndex={Math.min(currentPage * itemsPerPage, total)}
          sortedDataLength={total}
          itemsPerPage={itemsPerPage}
          setItemsPerPage={(v) => {
            setCurrentPage(1);
            setItemsPerPage(v);
          }}
        />
      )}
    </div>
  );
}