import React, { useState } from "react";
import { ChevronDown, ChevronUp, Search } from "lucide-react";
import { cn } from "@/lib/utils";
import Pagination from "@/components/Pagination";
import CircularProgress from "@mui/material/CircularProgress";
import { Checkbox } from "@mui/material";

// ------------------------
// TYPES
// ------------------------
export interface TableColumn<T> {
  key: keyof T;
  label: string;
  sortable?: boolean;
  render?: (value: any, row: T) => React.ReactNode;
}

interface DataTableProps<T> {
  columns: any[];
  data: T[];
  onRowClick?: (row: T) => void;
  actions?: (row: T) => React.ReactNode;
  status?: boolean;
  selectable?: boolean;
  selectableFactures?: T[];
  selectedIds?: string[];
  onSelectRow?: (id: string) => void;
  onSelectAll?: (checked: boolean) => void;
}

// ------------------------
// COMPONENT
// ------------------------
const DataTable = <T extends Record<string, any>>({
  columns,
  data,
  onRowClick,
  selectable = false,
  selectableFactures = [],
  selectedIds = [],
  onSelectRow,
  onSelectAll,
  actions,
  status = false,
}: DataTableProps<T>) => {
  const [sortColumn, setSortColumn] = useState<keyof T | null>(null);
  const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
  const [searchTerm, setSearchTerm] = useState("");
  const [currentPage, setCurrentPage] = useState(1);

  const itemsPerPage = 10;

  const handleSort = (column: keyof T) => {
    if (sortColumn === column) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc");
    } else {
      setSortColumn(column);
      setSortDirection("asc");
    }
  };

  // 🔍 Recherche
  const filteredData = data.filter((row) =>
    Object.values(row).some((value) =>
      String(value).toLowerCase().includes(searchTerm.toLowerCase())
    )
  );

  // ↕️ Tri
  const sortedData = [...filteredData].sort((a, b) => {
    if (!sortColumn) return 0;

    const aVal = a[sortColumn];
    const bVal = b[sortColumn];

    if (aVal < bVal) return sortDirection === "asc" ? -1 : 1;
    if (aVal > bVal) return sortDirection === "asc" ? 1 : -1;
    return 0;
  });

  // 📄 Pagination
  const paginatedData = sortedData.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  const totalPages = Math.ceil(filteredData.length / itemsPerPage);

  // ✅ Vérifier si une facture est sélectionnable
  const isSelectable = (row: T) => {
    return selectableFactures.some(f => (f as any).numero === (row as any).numero);
  };

  // ✅ Vérifier si toutes les factures sélectionnables sont sélectionnées
  const allSelectableSelected = selectableFactures.length > 0 && 
    selectableFactures.every(f => selectedIds.includes((f as any).numero));

  // ------------------------
  // JSX
  // ------------------------
  return (
    <div className="space-y-4">
      {/* 🔍 Barre de recherche */}
      <div className="flex items-center gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
          <input
            type="text"
            placeholder="Rechercher..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-10 pr-4 py-2.5 bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-[#007E45] text-gray-900 dark:text-white"
          />
        </div>
      </div>

      {/* TABLE */}
      <div className="bg-white dark:bg-gray-950 border border-gray-200 dark:border-gray-800 rounded-2xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50 dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800">
              <tr>
                {/* ✅ Colonne de sélection */}
                {selectable && (
                  <th className="px-6 py-3 w-10">
                    <Checkbox 
                      checked={allSelectableSelected}
                      indeterminate={selectedIds.length > 0 && !allSelectableSelected}
                      onChange={(e) => onSelectAll?.(e.target.checked)}
                      disabled={selectableFactures.length === 0}
                      sx={{
                        color: '#007E45',
                        '&.Mui-checked': {
                          color: '#007E45',
                        },
                        '&.MuiCheckbox-indeterminate': {
                          color: '#007E45',
                        },
                      }}
                    />
                  </th>
                )}

                {columns.map((column) => (
                  <th
                    key={String(column.key)}
                    onClick={() =>
                      column.sortable && handleSort(column.key)
                    }
                    className={cn(
                      "px-6 py-3 text-left text-xs text-gray-900 font-bold dark:text-gray-400 uppercase tracking-wider",
                      column.sortable &&
                        "cursor-pointer hover:text-gray-900 dark:hover:text-white"
                    )}
                  >
                    <div className="flex items-center gap-2">
                      {column.label}
                      {column.sortable &&
                        sortColumn === column.key &&
                        (sortDirection === "asc" ? (
                          <ChevronUp className="w-4 h-4" />
                        ) : (
                          <ChevronDown className="w-4 h-4" />
                        ))}
                    </div>
                  </th>
                ))}

                {actions && (
                  <th className="px-6 py-3 text-right text-xs font-semibold text-gray-600 dark:text-gray-400 uppercase tracking-wider">
                    Actions
                  </th>
                )}
              </tr>
            </thead>

            <tbody className="divide-y divide-gray-200 dark:divide-gray-800">
              {/* LOADING */}
              {status ? (
                <tr>
                  <td colSpan={100} className="p-5">
                    <div className="flex justify-center items-center py-10">
                      <CircularProgress size={48} />
                    </div>
                  </td>
                </tr>
              ) : (
                paginatedData.map((row, rowIndex) => {
                  const rowId = (row as any).numero;
                  const isRowSelectable = isSelectable(row);
                  const isSelected = selectedIds.includes(rowId);

                  return (
                    <tr
                      key={rowIndex}
                      onClick={() => !selectable && onRowClick?.(row)}
                      className={cn(
                        "hover:bg-gray-50 dark:hover:bg-gray-900 transition-colors",
                        !selectable && "cursor-pointer",
                        isSelected && "bg-green-50 dark:bg-green-900/20"
                      )}
                    >
                      {/* ✅ Checkbox de sélection */}
                      {selectable && (
                        <td className="px-6 py-4" onClick={(e) => e.stopPropagation()}>
                          <Checkbox
                            checked={isSelected}
                            disabled={!isRowSelectable}
                            onChange={() => isRowSelectable && onSelectRow?.(rowId)}
                            sx={{
                              color: '#007E45',
                              '&.Mui-checked': {
                                color: '#007E45',
                              },
                            }}
                          />
                        </td>
                      )}

                      {columns.map((column) => (
                        <td
                          key={String(column.key)}
                          className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white"
                          onClick={() => selectable && onRowClick?.(row)}
                        >
                          {column.render
                            ? column.render(row[column.key], row)
                            : row[column.key]}
                        </td>
                      ))}

                      {actions && (
                        <td className="px-6 py-4 whitespace-nowrap text-right text-sm">
                          <div
                            className="flex items-center justify-end gap-2"
                            onClick={(e) => e.stopPropagation()}
                          >
                            {actions(row)}
                          </div>
                        </td>
                      )}
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* PAGINATION */}
      {totalPages > 1 && (
        <Pagination
          currentPage={currentPage}
          totalPages={totalPages}
          onPageChange={setCurrentPage}
        />
      )}
    </div>
  );
};

export default DataTable;