import React, { useEffect, useState } from 'react';
import { Layout } from "@/components/ui/Layout";
import { DataTable } from "@/components/ui/DataTable";
import { FilterBar, filterConfigs } from "@/components/ui/FilterBar";
import { useDataManager, dataManagerConfigs } from "@/hooks/useDataManager";

// Custom Pagination Component for server-side pagination
function ServerPagination({ paginationInfo, onPageChange, onPageSizeChange }) {
    if (!paginationInfo || paginationInfo.totalPages <= 1) return null;

    return (
        <div className="flex flex-col items-end space-y-1 md:space-y-1 sm:space-y-0.5 py-2 md:py-2 sm:py-1">
            {/* Page Info */}
            <div className="text-xs md:text-xs sm:text-xs text-gray-600 font-sans">
                Page {paginationInfo.currentPage} of {paginationInfo.totalPages}
                ({paginationInfo.totalItems} total records)
            </div>

            {/* Pagination Buttons */}
            <div className="flex items-center justify-end space-x-0.5 md:space-x-0.5 sm:space-x-0.5">
                <button
                    onClick={() => onPageChange(paginationInfo.currentPage - 1)}
                    disabled={!paginationInfo.hasPrev}
                    className={`w-5 h-5 md:w-5 md:h-5 sm:w-4 sm:h-4 rounded-sm border text-xs md:text-xs sm:text-xs font-medium transition-colors font-sans ${
                        !paginationInfo.hasPrev
                            ? '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 = [];
                    const totalPages = paginationInfo.totalPages;
                    const currentPage = paginationInfo.currentPage;

                    // Always show first two pages
                    for (let i = 1; i <= Math.min(2, totalPages); i++) {
                        pages.push(
                            <button
                                key={i}
                                onClick={() => onPageChange(i)}
                                className={`w-5 h-5 md:w-5 md:h-5 sm:w-4 sm:h-4 rounded-sm border text-xs md:text-xs sm: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 md:w-5 md:h-5 sm:w-4 sm:h-4 flex items-center justify-center text-xs md:text-xs sm: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={() => onPageChange(i)}
                                        className={`w-5 h-5 md:w-5 md:h-5 sm:w-4 sm:h-4 rounded-sm border text-xs md:text-xs sm: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={() => onPageChange(paginationInfo.currentPage + 1)}
                    disabled={!paginationInfo.hasNext}
                    className={`w-5 h-5 md:w-5 md:h-5 sm:w-4 sm:h-4 rounded-sm border text-xs md:text-xs sm:text-xs font-medium transition-colors font-sans ${
                        !paginationInfo.hasNext
                            ? '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>
    );
}

// Constables page with real API integration
export function ConstablesPage() {
    // Use the reusable data manager hook
    const {
        data: constables,
        filteredData,
        currentData,
        isLoading,
        error,
        filters,
        updateFilters,
        paginationInfo,
        goToPage
    } = useDataManager(dataManagerConfigs.constables);

    // State for dynamic filter configuration
    const [dynamicPoliceStationFilter, setDynamicPoliceStationFilter] = useState(filterConfigs.policeStation);

    // Debug logging
    console.log('ConstablesPage - Data:', constables);
    console.log('ConstablesPage - PaginationInfo:', paginationInfo);
    console.log('ConstablesPage - CurrentData:', paginationInfo?.currentData);

    // Initialize filter with static config
    useEffect(() => {
        setDynamicPoliceStationFilter(filterConfigs.policeStation);
    }, []);

    // Update dynamic filter when data changes
    useEffect(() => {
        if (constables && constables.constables && Array.isArray(constables.constables)) {
            // Extract unique police stations from the data
            const uniquePoliceStations = [...new Set(
                constables.constables
                    .map(constable => constable.police_station)
                    .filter(station => station) // Remove null/undefined values
            )].sort(); // Sort alphabetically

            console.log('Updating dynamic police station filter with:', uniquePoliceStations);

            if (uniquePoliceStations.length > 0) {
                const newFilter = {
                    key: 'policeStation',
                    type: 'select',
                    label: 'Police Station',
                    placeholder: 'Select Police Station',
                    options: [
                        { value: 'all', label: 'All Police Stations' },
                        ...uniquePoliceStations.map(station => ({
                            value: station,
                            label: station
                        }))
                    ]
                };
                
                setDynamicPoliceStationFilter(newFilter);
                
                // Check if current filter selection is still valid
                if (filters.policeStation && filters.policeStation !== 'all') {
                    const isValidSelection = uniquePoliceStations.includes(filters.policeStation);
                    if (!isValidSelection) {
                        console.log('Current police station selection is no longer valid, resetting to all');
                        updateFilters({ policeStation: 'all' });
                    }
                }
            } else {
                // If no police stations found in data, keep the static fallback
                console.log('No police stations found in data, keeping static fallback');
                setDynamicPoliceStationFilter(filterConfigs.policeStation);
                
                // Reset police station filter if it was set to something specific
                if (filters.policeStation && filters.policeStation !== 'all') {
                    console.log('Resetting police station filter to all due to no data');
                    updateFilters({ policeStation: 'all' });
                }
            }
        } else if (!constables) {
            // If no data yet, use the static fallback
            console.log('No data yet, using static fallback');
            setDynamicPoliceStationFilter(filterConfigs.policeStation);
        }
    }, [constables]);

    // Safety check for data
    if (!constables || !paginationInfo) {
        return (
            <Layout title="Constables" currentPage="constables">
                <div className="flex-1 p-4 md:p-4 sm:p-3 bg-white">
                    <div className="flex items-center justify-center h-64 md:h-56 sm:h-48">
                        <div className="text-center">
                            <p className="text-gray-600 md:text-sm sm:text-xs mb-4 md:mb-3 sm:mb-2">
                                {isLoading ? 'Loading constables...' : 'No data available'}
                            </p>
                            {!isLoading && (
                                <button 
                                    onClick={() => window.location.reload()} 
                                    className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md text-sm md:text-sm sm:text-xs"
                                >
                                    Retry
                                </button>
                            )}
                        </div>
                    </div>
                </div>
            </Layout>
        );
    }



    // Define table columns
    const columns = [
        {
            key: "login_id",
            header: "Login ID"
        },
        {
            key: "name",
            header: "Name"
        },
        {
            key: "police_station",
            header: "Police Station"
        },
        {
            key: "mobile",
            header: "Mobile Number"
        }
    ];

    // Handle row click (if needed)
    const handleRowClick = (constable) => {
        console.log('Clicked constable:', constable);
        // Add navigation or modal logic here
    };

    if (isLoading) {
        return (
            <Layout title="Constables" currentPage="constables">
                <div className="flex-1 p-4 md:p-4 sm:p-3 bg-white">
                    <div className="flex items-center justify-center h-64 md:h-56 sm:h-48">
                        <div className="text-center">
                            <div className="animate-spin rounded-full h-12 w-12 md:h-10 md:w-10 sm:h-8 sm:w-8 border-b-2 border-blue-600 mx-auto mb-4 md:mb-3 sm:mb-2"></div>
                            <p className="text-gray-600 md:text-sm sm:text-xs">Loading constables...</p>
                        </div>
                    </div>
                </div>
            </Layout>
        );
    }

    if (error) {
        return (
            <Layout title="Constables" currentPage="constables">
                <div className="flex-1 p-4 md:p-4 sm:p-3 bg-white">
                    <div className="flex items-center justify-center h-64 md:h-56 sm:h-48">
                        <div className="text-center">
                            <p className="text-red-600 md:text-sm sm:text-xs mb-4 md:mb-3 sm:mb-2">Error loading constables: {error}</p>
                            <button 
                                onClick={() => window.location.reload()} 
                                className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md text-sm md:text-sm sm:text-xs"
                            >
                                Retry
                            </button>
                        </div>
                    </div>
                </div>
            </Layout>
        );
    }

    return (
        <Layout title="Constables" currentPage="constables">
            {/* Main Content Container */}
            <div className="flex-1 p-4 md:p-4 sm:p-3 space-y-4 md:space-y-3 sm:space-y-2 bg-white font-inter">
                {/* Filters */}
                <FilterBar
                    filters={filters}
                    onFilterChange={updateFilters}
                    filterConfigs={[dynamicPoliceStationFilter]}
                    showSearch={true}
                    searchPlaceholder="Search constables..."
                    className="mb-2 md:mb-2 sm:mb-1"
                />
                
                            {/* Data Table */}
            <DataTable
                data={paginationInfo.currentData || []}
                columns={columns}
                searchable={false} // Search is handled by FilterBar
                pagination={false} // Disable internal pagination, use custom server-side pagination
                pageSize={paginationInfo.pageSize}
                emptyMessage={
                    !paginationInfo.currentData 
                        ? "Loading constables..." 
                        : paginationInfo.currentData.length === 0 
                            ? "No constables found." 
                            : "No constables match the current filters."
                }
                onRowClick={handleRowClick}
                className="mt-4 md:mt-3 sm:mt-2"
                rowClassName="hover:bg-gray-50 transition-colors"
                cellClassName="py-4 md:py-3 sm:py-2"
            />

                {/* Custom Server-Side Pagination */}
                {paginationInfo && paginationInfo.totalPages > 0 ? (
                    <ServerPagination
                        paginationInfo={paginationInfo}
                        onPageChange={goToPage}
                    />
                ) : (
                    <div className="text-center text-gray-500 text-sm md:text-sm sm:text-xs mt-4 md:mt-3 sm:mt-2">
                        {paginationInfo ? 'No pagination data available' : 'Loading pagination...'}
                    </div>
                )}
            </div>
        </Layout>
      );
  }
