/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import React, { useState } from 'react';
import { Search, Download, ChevronLeft, ChevronRight, Filter } from 'lucide-react';
import { BiArrowBack } from 'react-icons/bi';
import { useRouter } from 'next/navigation';

interface Column {
  key: string;
  label: string;
  render?: (value: any, row: any) => React.ReactNode;
}

interface DataTableProps {
  columns: Column[];
  data: any[];
  itemsPerPage?: number;
  showSearch?: boolean;
  showFilter?: boolean;
  showDownload?: boolean;
  onFilterClick?: () => void;
  onDownloadClick?: () => void;
}

export const DataTable: React.FC<DataTableProps> = ({
  columns,
  data,
  itemsPerPage = 50,
  showSearch = true,
  showFilter = true,
  showDownload = true,
  onFilterClick,
  onDownloadClick,
}) => {
  const router = useRouter()
  const [currentPage, setCurrentPage] = useState(1);
  const [searchQuery, setSearchQuery] = useState('');

  // Filter data based on search query
  const filteredData = data.filter((row) =>
    columns.some((column) => {
      const value = row[column.key];
      return value?.toString().toLowerCase().includes(searchQuery.toLowerCase());
    })
  );

  // Pagination calculations
  const totalPages = Math.ceil(filteredData.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentData = filteredData.slice(startIndex, endIndex);
  const startItem = startIndex + 1;
  const endItem = Math.min(endIndex, filteredData.length);

  const handlePrevious = () => {
    if (currentPage > 1) setCurrentPage(currentPage - 1);
  };

  const handleNext = () => {
    if (currentPage < totalPages) setCurrentPage(currentPage + 1);
  };

  return (
    <div className="p-4 md:p-6">
      {/* Header with Search and Actions */}
        <button
          type="button"
          onClick={() => router.back()}
          className="transition cursor-pointer flex text-gray-600 items-center gap-2.5 mb-10"
          title="Back"
          >
        <BiArrowBack size={20} className="text-gray-600" />
        <span>Back</span>
      </button>
      
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">

        {/* Search Bar */}
        {showSearch && (
          <div className="relative w-full md:w-96">
            <Search className="absolute left-4 top-1/2 transform -translate-y-1/2 text-gray-400" size={20} />
            <input
              type="text"
              placeholder="Search"
              value={searchQuery}
              onChange={(e) => {
                setSearchQuery(e.target.value);
                setCurrentPage(1); // Reset to first page on search
              }}
              className="w-full pl-12 pr-4 py-3 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            />
          </div>
        )}

        {/* Right Actions */}
        <div className="flex items-center gap-4">
          {showDownload && (
            <button
              type="button"
              onClick={onDownloadClick}
              className="p-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition cursor-pointer"
              title="Download"
            >
              <Download size={20} className="text-gray-600" />
            </button>
          )}
          
          {/* Pagination Info */}
          <span className="text-sm text-gray-600 whitespace-nowrap">
            {startItem}-{endItem} of {filteredData.length}
          </span>

          {/* Pagination Buttons */}
          <div className="flex gap-2">
            <button
              onClick={handlePrevious}
              disabled={currentPage === 1}
              className={`p-2 border border-gray-300 rounded-lg transition ${
                currentPage === 1
                  ? 'text-gray-300 cursor-not-allowed'
                  : 'text-gray-600 hover:bg-gray-50'
              }`}
            >
              <ChevronLeft size={20} />
            </button>
            <button
              onClick={handleNext}
              disabled={currentPage === totalPages}
              className={`p-2 border border-gray-300 rounded-lg transition ${
                currentPage === totalPages
                  ? 'text-gray-300 cursor-not-allowed'
                  : 'text-gray-600 hover:bg-gray-50'
              }`}
            >
              <ChevronRight size={20} />
            </button>
          </div>
        </div>
      </div>

      {/* Filter Button */}
      {showFilter && (
        <div className="mb-6">
          <button
            onClick={onFilterClick}
            className="flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition"
          >
            <Filter size={18} className="text-gray-600" />
            <span className="text-sm text-gray-600">Filter</span>
          </button>
        </div>
      )}

      {/* Table */}
      <div className="border border-gray-200 rounded-lg overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-white border-b border-gray-200">
              <tr>
                {columns.map((column) => (
                  <th
                    key={column.key}
                    className="px-6 py-4 text-left text-sm font-semibold text-gray-700"
                  >
                    {column.label}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {currentData.length > 0 ? (
                currentData.map((row, index) => (
                  <tr key={index} className="hover:bg-gray-50 transition">
                    {columns.map((column) => (
                      <td key={column.key} className="px-6 py-4 text-sm text-gray-700">
                        {column.render
                          ? column.render(row[column.key], row)
                          : row[column.key]}
                      </td>
                    ))}
                  </tr>
                ))
              ) : (
                <tr>
                  <td
                    colSpan={columns.length}
                    className="px-6 py-12 text-center text-gray-500"
                  >
                    No data found
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};