import { useState, useMemo } from 'react';
import { ChevronLeft, ChevronRight, Search, Filter, Download } from 'lucide-react';

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

interface EnhancedDataTableProps {
  data: any[];
  columns: Column[];
  itemsPerPage?: number;
  searchable?: boolean;
  exportable?: boolean;
  className?: string;
}

const EnhancedDataTable: React.FC<EnhancedDataTableProps> = ({
  data,
  columns,
  itemsPerPage = 10,
  searchable = true,
  exportable = true,
  className = ''
}) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [searchTerm, setSearchTerm] = useState('');
  const [sortConfig, setSortConfig] = useState<{
    key: string;
    direction: 'asc' | 'desc';
  } | null>(null);

  // Filter and search data
  const filteredData = useMemo(() => {
    return data.filter(item =>
      columns.some(column =>
        String(item[column.key] || '')
          .toLowerCase()
          .includes(searchTerm.toLowerCase())
      )
    );
  }, [data, searchTerm, columns]);

  // Sort data
  const sortedData = useMemo(() => {
    if (!sortConfig) return filteredData;

    return [...filteredData].sort((a, b) => {
      const aValue = a[sortConfig.key];
      const bValue = b[sortConfig.key];

      if (aValue < bValue) {
        return sortConfig.direction === 'asc' ? -1 : 1;
      }
      if (aValue > bValue) {
        return sortConfig.direction === 'asc' ? 1 : -1;
      }
      return 0;
    });
  }, [filteredData, sortConfig]);

  // Paginate data
  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return sortedData.slice(startIndex, startIndex + itemsPerPage);
  }, [sortedData, currentPage, itemsPerPage]);

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

  const handleSort = (columnKey: string) => {
    const column = columns.find(col => col.key === columnKey);
    if (!column?.sortable) return;

    setSortConfig(current => ({
      key: columnKey,
      direction: 
        current?.key === columnKey && current.direction === 'asc' 
          ? 'desc' 
          : 'asc'
    }));
  };

  const exportToCSV = () => {
    const headers = columns.map(col => col.label).join(',');
    const rows = sortedData.map(row =>
      columns.map(col => `"${row[col.key] || ''}"`).join(',')
    ).join('\n');
    
    const csvContent = `${headers}\n${rows}`;
    const blob = new Blob([csvContent], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'table-data.csv';
    a.click();
    window.URL.revokeObjectURL(url);
  };

  const goToPage = (page: number) => {
    setCurrentPage(Math.max(1, Math.min(page, totalPages)));
  };

  const renderPaginationButtons = () => {
    const buttons = [];
    const maxVisible = 5;
    const start = Math.max(1, currentPage - Math.floor(maxVisible / 2));
    const end = Math.min(totalPages, start + maxVisible - 1);

    for (let i = start; i <= end; i++) {
      buttons.push(
        <button
          key={i}
          onClick={() => goToPage(i)}
          className={`px-3 py-2 text-sm rounded-lg ${
            i === currentPage
              ? 'bg-primary text-white'
              : 'bg-white text-gray-700 hover:bg-gray-50 border border-gray-300'
          }`}
        >
          {i}
        </button>
      );
    }

    return buttons;
  };

  return (
    <div className={`card-enhanced ${className}`}>
      {/* Table Header */}
      <div className="card-header border-bottom-0 pb-0" style={{ position: 'relative' }}>
        <div className="d-flex justify-content-between align-items-center" style={{ paddingLeft: '16px' }}>
          <h5 className="card-title mb-0">Data Table</h5>
          
          <div className="d-flex gap-2">
            {searchable && (
              <div className="position-relative">
                <Search className="position-absolute start-0 top-50 translate-middle-y ms-3" size={16} />
                <input
                  type="text"
                  placeholder="Search..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="form-control-enhanced ps-5"
                  style={{ width: '200px' }}
                />
              </div>
            )}
            
            {exportable && (
              <button
                onClick={exportToCSV}
                className="btn btn-outline-primary btn-sm d-flex align-items-center gap-2"
                data-tooltip="Export to CSV"
              >
                <Download size={16} />
                Export
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Table */}
      <div className="card-body p-0">
        <div className="table-responsive">
          <table className="table table-hover mb-0">
            <thead>
              <tr style={{ backgroundColor: '#f8e8e5' }}>
                {columns.map((column) => (
                  <th
                    key={column.key}
                    className={`text-uppercase ${column.sortable ? 'cursor-pointer user-select-none' : ''}`}
                    style={{ 
                      fontSize: '11px', 
                      fontWeight: 600, 
                      letterSpacing: '1px',
                      padding: '0.8rem 1rem'
                    }}
                    onClick={() => handleSort(column.key)}
                  >
                    <div className="d-flex align-items-center gap-2">
                      {column.label}
                      {column.sortable && (
                        <div className="d-flex flex-column">
                          <i 
                            className={`bi bi-caret-up-fill ${
                              sortConfig?.key === column.key && sortConfig.direction === 'asc'
                                ? 'text-primary'
                                : 'text-muted'
                            }`}
                            style={{ fontSize: '8px', lineHeight: '1' }}
                          ></i>
                          <i 
                            className={`bi bi-caret-down-fill ${
                              sortConfig?.key === column.key && sortConfig.direction === 'desc'
                                ? 'text-primary'
                                : 'text-muted'
                            }`}
                            style={{ fontSize: '8px', lineHeight: '1' }}
                          ></i>
                        </div>
                      )}
                    </div>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {paginatedData.map((row, index) => (
                <tr key={index} className="border-bottom">
                  {columns.map((column) => (
                    <td key={column.key} style={{ padding: '0.8rem 1rem' }}>
                      {column.render
                        ? column.render(row[column.key], row)
                        : row[column.key]
                      }
                    </td>
                  ))}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        
        {paginatedData.length === 0 && (
          <div className="text-center py-5 text-muted">
            <p>No data found</p>
          </div>
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="card-footer bg-transparent border-top">
          <div className="d-flex justify-content-between align-items-center">
            <div className="text-muted small">
              Showing {((currentPage - 1) * itemsPerPage) + 1} to{' '}
              {Math.min(currentPage * itemsPerPage, sortedData.length)} of{' '}
              {sortedData.length} entries
            </div>
            
            <div className="d-flex gap-1">
              <button
                onClick={() => goToPage(currentPage - 1)}
                disabled={currentPage === 1}
                className="btn btn-outline-secondary btn-sm d-flex align-items-center gap-1"
              >
                <ChevronLeft size={16} />
                Previous
              </button>
              
              {renderPaginationButtons()}
              
              <button
                onClick={() => goToPage(currentPage + 1)}
                disabled={currentPage === totalPages}
                className="btn btn-outline-secondary btn-sm d-flex align-items-center gap-1"
              >
                Next
                <ChevronRight size={16} />
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default EnhancedDataTable;