"use client";

import React, { useEffect, useState, useCallback } from "react";
import styles from "../../commonstyle/dattabale.module.css";
import { FaSearchLocation } from "react-icons/fa";
import { FiRefreshCw, FiEdit, FiTrash2, FiPlus } from "react-icons/fi";
import { EnterpriseLoader } from "./../../../../../components/loader/loader";
import { deleteWithConfirm } from "./../../../../../components/ConfirmDialog/ConfirmDialog";
import {
  getAuditStagesPaginated,
  deleteAuditStage,
} from "@/lib/api/auditStage.api";
import { mapAuditStagesToRows } from "@/lib/api/mappers/auditStage.mappers";
import { useModulePermissions } from "@/lib/api/hooks/useModulePermissions";
import AuditStageForm from "./AuditStageForm";
import type { AuditStageRow } from "@/lib/api/types/auditStage.types";

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 AuditStageTable() {
  const [rows, setRows]       = useState<AuditStageRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError]     = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState("");
  const debouncedSearch = useDebounce(searchTerm, 350);

  // ── Modal state ──────────────────────────────────────────────────────────
  const [isFormOpen, setIsFormOpen]   = useState(false);
  const [editingId, setEditingId]     = useState<number | null>(null);

  const { canPerform } = useModulePermissions("audit-stages");
  // ── Fetch ────────────────────────────────────────────────────────────────
  const fetchStages = useCallback(async (search = "") => {
    setLoading(true);
    setError(null);
    try {
      const res = await getAuditStagesPaginated({ page: 1, limit: 200, search: search || undefined });
      const data = Array.isArray(res) ? res : (res.data ?? []);
      setRows(mapAuditStagesToRows(data));
    } catch (err: any) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchStages(debouncedSearch); }, [debouncedSearch, fetchStages]);

  const handleDelete = async (row: AuditStageRow) => {
    const { confirmed, error: delErr } = await deleteWithConfirm(
      row.name,
      () => deleteAuditStage(row.id),
      { successMessage: "Stage deleted.", errorMessage: "Failed to delete." }
    );
    if (confirmed && !delErr) fetchStages(debouncedSearch);
  };

  const openEdit = (row: AuditStageRow) => { setEditingId(row.id); setIsFormOpen(true); };
  const openNew  = () => { setEditingId(null); setIsFormOpen(true); };

  if (error) return (
    <div className={styles.errorContainer}>
      <div className={styles.errorIcon}>⚠️</div>
      <h3 className={styles.errorTitle}>Error loading stages</h3>
      <p className={styles.errorMessage}>{error}</p>
      <button className={styles.errorButton} onClick={() => fetchStages("")}>Retry</button>
    </div>
  );

  return (
    <div className={styles.container}>

      {/* ── 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 stages"
              placeholder="Search audit stage names..."
              className={styles.searchInput}
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>
          <div className={styles.toolbarActions}>
            {canPerform("create") && (
              <button
                className={styles.btnPrimary}
                style={{ background: "linear-gradient(135deg, #581c87, #7c3aed)", display: "flex", alignItems: "center", gap: 6 }}
                onClick={openNew}
              >
                <FiPlus size={16} /> New Stage
              </button>
            )}
            <button className={styles.btnIcon} title="Refresh" onClick={() => fetchStages(debouncedSearch)}>
              <FiRefreshCw size={16} />
            </button>
          </div>
        </div>
      </div>

      {/* ── Record count ── */}
      {!loading && (
        <div style={{
          padding: "10px 16px", backgroundColor: "#f5f3ff", border: "1px solid #ddd6fe",
          borderRadius: 8, marginBottom: 12, fontSize: 13, color: "#6d28d9",
        }}>
          ⚙️ <strong>{rows.length}</strong> audit stage{rows.length !== 1 ? "s" : ""} configured
          <span style={{ color: "#9ca3af", marginLeft: 8 }}>— used by Company Audits as lookup values</span>
        </div>
      )}

      {/* ── Table ── */}
      {loading ? <EnterpriseLoader /> : (
        <div className={styles.tableWrapper}>
          <table className={styles.table}>
            <thead>
              <tr>
                <th className={styles.th} style={{ width: 50 }}>#</th>
                <th className={styles.th}>Stage Name</th>
                <th className={styles.th}>Description</th>
                <th className={styles.th} style={{ width: 80 }}>Order</th>
                <th className={styles.th}>Created</th>
                <th className={styles.actionsCol}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {rows.length > 0 ? rows.map((row) => (
                <tr key={row.id} className={styles.tableRow}>
                  <td className={styles.nameCell} style={{ color: "#9ca3af", fontSize: 12 }}>#{row.id}</td>

                  {/* Stage Name with pill badge */}
                  <td className={styles.nameCell}>
                    <span style={{
                      display: "inline-flex", alignItems: "center", gap: 6,
                      padding: "4px 12px", borderRadius: 20, fontSize: 13, fontWeight: 600,
                      background: "#f5f3ff", color: "#6d28d9", border: "1px solid #ddd6fe",
                    }}>
                      ⚙️ {row.name}
                    </span>
                  </td>

                  <td className={styles.nameCell} style={{ color: "#6b7280", fontSize: 13 }}>
                    {row.description === "—" ? (
                      <span style={{ color: "#d1d5db", fontStyle: "italic" }}>No description</span>
                    ) : row.description}
                  </td>

                  <td className={styles.nameCell} style={{ textAlign: "center" }}>
                    {row.order ? (
                      <span style={{ padding: "2px 10px", borderRadius: 12, fontSize: 11, fontWeight: 700, background: "#e0e7ff", color: "#3730a3" }}>
                        {row.order}
                      </span>
                    ) : "—"}
                  </td>

                  <td className={styles.nameCell} style={{ color: "#6b7280", fontSize: 13 }}>
                    {row.created_at}
                  </td>

                  <td className={styles.actionsCell}>
                    <div className={styles.actionGroup}>
                      {canPerform("edit") && (
                        <button
                          className={styles.actionBtnEdit}
                          onClick={() => openEdit(row)}
                          title="Edit Stage"
                        >
                          <FiEdit size={14} />
                        </button>
                      )}
                      {canPerform("delete") && (
                        <button
                          className={styles.actionBtnDelete}
                          onClick={() => handleDelete(row)}
                          title="Delete Stage"
                        >
                          <FiTrash2 size={14} />
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              )) : (
                <tr>
                  <td colSpan={6} style={{ textAlign: "center", padding: 60 }}>
                    <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 12 }}>
                      <div style={{ fontSize: 36 }}>⚙️</div>
                      <h3 style={{ margin: 0, color: "#111827" }}>No Audit Stages Configured</h3>
                      <p style={{ color: "#6b7280", margin: 0 }}>
                        {searchTerm
                          ? "No stages match your search."
                          : "Add your first audit stage to get started."}
                      </p>
                      {!searchTerm && canPerform("create") && (
                        <button
                          onClick={openNew}
                          style={{ padding: "10px 24px", background: "#7c3aed", color: "#fff", border: "none", borderRadius: 8, fontWeight: 600, cursor: "pointer" }}
                        >
                          + New Audit Stage
                        </button>
                      )}
                    </div>
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}

      {/* ── Form modal ── */}
      <AuditStageForm
        isOpen={isFormOpen}
        onClose={() => { setIsFormOpen(false); setEditingId(null); }}
        refreshData={() => fetchStages(debouncedSearch)}
        editId={editingId}
      />
    </div>
  );
}
