import React, { useState, useMemo } from 'react';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { Search } from 'lucide-react';

export function DataTable({ 
    data = [], 
    columns = [], 
    searchable = true,
    searchPlaceholder = "Search...",
    searchFields = [],
    pagination = true,
    pageSize = 20,
    className = "",
    emptyMessage = "No data found.",
    onRowClick = null,
    rowClassName = "",
    headerClassName = "",
    cellClassName = ""
}) {
    const [currentPage, setCurrentPage] = useState(1);
    const [searchTerm, setSearchTerm] = useState('');

    // Filter data based on search term
    const filteredData = useMemo(() => {
        if (!searchable || !searchTerm.trim()) return data;
        
        return data.filter(item => {
            if (searchFields.length === 0) {
                // Search in all string/number fields
                return Object.values(item).some(value => 
                    String(value).toLowerCase().includes(searchTerm.toLowerCase())
                );
            }
            
            // Search in specific fields
            return searchFields.some(field => {
                const value = item[field];
                return String(value).toLowerCase().includes(searchTerm.toLowerCase());
            });
        });
    }, [data, searchTerm, searchable, searchFields]);

    // Pagination logic
    const totalPages = Math.ceil(filteredData.length / pageSize);
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const currentData = filteredData.slice(startIndex, endIndex);

    // Handle page change
    const handlePageChange = (page) => {
        setCurrentPage(page);
    };

    // Handle next page
    const handleNextPage = () => {
        if (currentPage < totalPages) {
            setCurrentPage(currentPage + 1);
        }
    };

    // Handle previous page
    const handlePreviousPage = () => {
        if (currentPage > 1) {
            setCurrentPage(currentPage - 1);
        }
    };

    // Reset to first page when search changes
    React.useEffect(() => {
        setCurrentPage(1);
    }, [searchTerm]);

    // Handle row click
    const handleRowClick = (item) => {
        if (onRowClick) {
            onRowClick(item);
        }
    };

    return (
        <div className={`space-y-4 ${className}`}>
            {/* Search Bar */}
            {searchable && (
                <div className="relative max-w-md">
                    <Search className="absolute left-2 top-1/2 transform -translate-y-1/2 text-gray-400 w-3 h-3" />
                    <Input
                        placeholder={searchPlaceholder}
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className="pl-8 font-sans"
                    />
                </div>
            )}

            {/* Record Count */}
            <div className="text-xs text-gray-600 font-sans">
                Total records: {filteredData.length}
            </div>

            {/* Table */}
            <div className="bg-white rounded-lg border border-gray-200 overflow-hidden">
                <div className="overflow-x-auto">
                    <Table>
                        <TableHeader>
                            <TableRow className="bg-gray-50">
                                {columns.map((column, index) => (
                                    <TableHead 
                                        key={index}
                                        className={`text-left text-xs font-bold text-gray-600 py-1 px-2 font-sans ${headerClassName}`}
                                    >
                                        {column.header}
                                    </TableHead>
                                ))}
                            </TableRow>
                        </TableHeader>
                        <TableBody>
                            {currentData.length > 0 ? (
                                currentData.map((item, rowIndex) => (
                                    <TableRow 
                                        key={item.id || rowIndex} 
                                        className={`${rowClassName} ${onRowClick ? 'cursor-pointer' : ''}`}
                                        onClick={() => handleRowClick(item)}
                                    >
                                        {columns.map((column, colIndex) => (
                                            <TableCell 
                                                key={colIndex}
                                                className={`text-xs text-gray-900 py-1 px-2 font-sans ${cellClassName}`}
                                            >
                                                {column.render ? column.render(item[column.key], item) : item[column.key]}
                                            </TableCell>
                                        ))}
                                    </TableRow>
                                ))
                            ) : (
                                <TableRow>
                                    <TableCell 
                                        colSpan={columns.length} 
                                        className="h-8 text-center text-xs text-gray-500 font-sans"
                                    >
                                        {emptyMessage}
                                    </TableCell>
                                </TableRow>
                            )}
                        </TableBody>
                    </Table>
                </div>
            </div>

            {/* Pagination Controls */}
            {pagination && totalPages > 1 && (
                <div className="flex flex-col items-end space-y-1 py-2">
                    {/* Page Info */}
                    <div className="text-xs text-gray-600 font-sans">
                        Page {currentPage} of {totalPages}
                        ({filteredData.length} total records)
                    </div>

                    {/* Pagination Buttons */}
                    <div className="flex items-center justify-end space-x-0.5">
                        <button
                            onClick={handlePreviousPage}
                            disabled={currentPage === 1}
                            className={`w-5 h-5 rounded-sm border text-xs font-medium transition-colors font-sans ${
                                currentPage === 1
                                    ? 'bg-gray-100 text-gray-400 cursor-not-allowed border-gray-200'
                                    : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-200'
                            }`}
                        >
                            ‹
                        </button>

                        {(() => {
                            const pages = [];

                            // Always show first two pages
                            for (let i = 1; i <= Math.min(2, totalPages); i++) {
                                pages.push(
                                    <button
                                        key={i}
                                        onClick={() => handlePageChange(i)}
                                        className={`w-5 h-5 rounded-sm border text-xs font-medium transition-colors font-sans ${
                                            currentPage === i
                                                ? 'bg-blue-600 text-white border-blue-600'
                                                : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-200'
                                        }`}
                                    >
                                        {i}
                                    </button>
                                );
                            }

                            // Add ellipsis if there are more than 4 pages
                            if (totalPages > 4) {
                                pages.push(
                                    <span key="ellipsis" className="w-5 h-5 flex items-center justify-center text-xs text-gray-600 border border-gray-200 rounded-sm font-sans">
                                        ...
                                    </span>
                                );
                            }

                            // Show last two pages (if different from first two)
                            if (totalPages > 2) {
                                for (let i = Math.max(3, totalPages - 1); i <= totalPages; i++) {
                                    if (i > 2) { // Avoid duplicate pages
                                        pages.push(
                                            <button
                                                key={i}
                                                onClick={() => handlePageChange(i)}
                                                className={`w-5 h-5 rounded-sm border text-xs font-medium transition-colors font-sans ${
                                                    currentPage === i
                                                        ? 'bg-blue-600 text-white border-blue-600'
                                                        : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-200'
                                                }`}
                                            >
                                                {i}
                                            </button>
                                        );
                                    }
                                }
                            }

                            return pages;
                        })()}

                        <button
                            onClick={handleNextPage}
                            disabled={currentPage === totalPages}
                            className={`w-5 h-5 rounded-sm border text-xs font-medium transition-colors font-sans ${
                                currentPage === totalPages
                                    ? 'bg-gray-100 text-gray-400 cursor-not-allowed border-gray-200'
                                    : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-200'
                            }`}
                        >
                            ›
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
}
