import React, { useState, useRef, useEffect } from 'react';
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Calendar } from "@/components/ui/calendar";
import { Calendar as CalendarIcon } from "lucide-react";
import { format } from "date-fns";
import { cn } from "@/lib/utils";
import { DateRangePicker } from "@/components/ui/DateRangePicker";

export function ViolationFilters({ 
    filters, 
    setFilters, 
    violationTypes = [],
    isLoadingViolationTypes = false,
    violationTypesError = null,
    onRetryViolationTypes = null,
    counts = {
        totalCount: 0,
        newCount: 0,
        raisedCount: 0,
        rejectedCount: 0
    },
    className = ""
}) {
    const [showViolationTypesDropdown, setShowViolationTypesDropdown] = useState(false);
    const violationTypesContainerRef = useRef(null);

    // Function to calculate dropdown position
    const getDropdownPosition = () => {
        if (!violationTypesContainerRef.current) return 'left-0';
        
        const container = violationTypesContainerRef.current;
        const rect = container.getBoundingClientRect();
        const viewportWidth = window.innerWidth;
        
        // If dropdown would overflow to the right, position it to the right of the container
        if (rect.left + 320 > viewportWidth - 20) {
            return 'right-0';
        }
        
        return 'left-0';
    };

    // Handle clicks outside violation types dropdown to close it
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (showViolationTypesDropdown && !event.target.closest('.violation-types-container')) {
                setShowViolationTypesDropdown(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [showViolationTypesDropdown]);

    // Handler for the text search input
    const handleSearchChange = (e) => {
        setFilters(prev => ({ ...prev, search: e.target.value }));
    };

    // Handler for the status dropdown
    const handleStatusChange = (value) => {
        setFilters(prev => ({ ...prev, status: value === 'all' ? 'all' : value }));
    };

    // Handler for the date picker
    const handleDateChange = (dateRange) => {
        setFilters(prev => ({ ...prev, dateRange }));
    };

    return (
        <div className={`space-y-4 ${className}`}>
            {/* Status Tabs */}
            <div className="flex flex-wrap md:flex-nowrap sm:flex-wrap space-x-2 md:space-x-2 sm:space-x-1 bg-white rounded-lg -mb-6 overflow-x-auto">
                <button
                    onClick={() => setFilters(prev => ({ ...prev, status: 'all' }))}
                    className={`py-2 md:py-2 sm:py-1.5 px-4 md:px-4 sm:px-3 rounded-md text-xs font-medium transition-colors ${filters.status === 'all'
                        ? 'bg-gray-100 text-black shadow-sm'
                        : 'bg-white text-black hover:bg-gray-50'
                        }`}
                >
                    <span className="font-bold">All</span>
                    <span className="ml-2 md:ml-2 sm:ml-1 bg-purple-100 text-purple-600 px-2 md:px-2 sm:px-1.5 py-1 md:py-1 sm:py-0.5 rounded-full text-xs">
                        {counts.totalCount > 0 ? counts.totalCount : 'No Data'}
                    </span>
                </button>
                <button
                    onClick={() => setFilters(prev => ({ ...prev, status: 'New' }))}
                    className={`py-2 md:py-2 sm:py-1.5 px-4 md:px-4 sm:px-3 rounded-md text-xs font-medium transition-colors ${filters.status === 'New'
                        ? 'bg-gray-100 text-black shadow-sm'
                        : 'bg-white text-black hover:bg-gray-50'
                        }`}
                >
                    <span>New</span>
                    <span className="ml-2 md:ml-2 sm:ml-1 bg-blue-100 text-blue-800 px-2 md:px-2 sm:px-1.5 py-1 md:py-1 sm:py-0.5 rounded-full text-xs">
                        {counts.newCount > 0 ? counts.newCount : 'No Data'}
                    </span>
                </button>
                <button
                    onClick={() => setFilters(prev => ({ ...prev, status: 'Raised' }))}
                    className={`py-2 md:py-2 sm:py-1.5 px-4 md:px-4 sm:px-3 rounded-md text-xs font-medium transition-colors ${filters.status === 'Raised'
                        ? 'bg-gray-100 text-black shadow-sm'
                        : 'bg-white text-black hover:bg-gray-50'
                        }`}
                >
                    <span>Raised</span>
                    <span className="ml-2 md:ml-2 sm:ml-1 bg-green-100 text-green-600 px-2 md:px-2 sm:px-1.5 py-1 md:py-1 sm:py-0.5 rounded-full text-xs">
                        {counts.raisedCount > 0 ? counts.raisedCount : 'No Data'}
                    </span>
                </button>
                <button
                    onClick={() => setFilters(prev => ({ ...prev, status: 'Rejected' }))}
                    className={`py-2 md:py-2 sm:py-1.5 px-4 md:px-4 sm:px-3 rounded-md text-xs font-medium transition-colors ${filters.status === 'Rejected'
                        ? 'bg-gray-100 text-black shadow-sm'
                        : 'bg-white text-black hover:bg-gray-50'
                        }`}
                >
                    <span>Rejected</span>
                    <span className="ml-2 md:ml-2 sm:ml-1 bg-yellow-100 text-yellow-600 px-2 md:px-2 sm:px-1.5 py-1 md:py-1 sm:py-0.5 rounded-full text-xs">
                        {counts.rejectedCount > 0 ? counts.rejectedCount : 'No Data'}
                    </span>
                </button>
            </div>

            {/* Search and Filter Controls */}
            <div className="flex flex-col md:flex-row sm:flex-col items-start md:items-center sm:items-start gap-2 md:gap-2 sm:gap-2 w-full md:w-auto sm:w-full">
                <div className="w-full md:w-48 sm:w-full min-w-0">
                    <label className="block text-xs text-gray-600 mb-1">Search</label>
            <Input
                        placeholder="Search by ID/license plate"
                value={filters.search}
                onChange={handleSearchChange}
                        className="text-sm w-full"
                    />
                </div>

                <div className="w-full md:w-48 sm:w-full min-w-0">
                    <label className="block text-xs text-gray-600 mb-1">Time Range</label>
                    <DateRangePicker
                        value={filters.dateRange}
                        onValueChange={handleDateChange}
                        placeholder="Select time range"
                        className="w-full md:w-48 sm:w-full h-10 md:h-10 sm:h-9 px-3 md:px-3 sm:px-2 py-2 text-sm"
                    />
                </div>

                <div className="w-full md:w-48 sm:w-full min-w-0 violation-types-container" ref={violationTypesContainerRef}>
                    <label className="block text-xs text-gray-600 mb-1">Violation Types</label>
                    <div className="relative">
                        {/* Multi-select dropdown trigger */}
                        <button
                            type="button"
                            onClick={() => setShowViolationTypesDropdown(!showViolationTypesDropdown)}
                            className="w-full flex items-center justify-between px-3 md:px-3 sm:px-2 py-2 md:py-2 sm:py-1.5 text-sm bg-white border border-gray-300 rounded-md hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                        >
                            <span className="truncate">
                                {filters.violationTypes.length === 0 
                                    ? "All Types" 
                                    : filters.violationTypes.length === 1 
                                        ? filters.violationTypes[0] 
                                        : `${filters.violationTypes.length} types selected`
                                }
                            </span>
                            <svg className={`w-4 h-4 md:w-4 md:h-4 sm:w-3.5 sm:h-3.5 text-gray-400 transition-transform ${showViolationTypesDropdown ? 'rotate-180' : ''}`} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                            </svg>
                        </button>

                        {/* Multi-select dropdown content */}
                        {showViolationTypesDropdown && (
                            <div className={`absolute top-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg z-50 max-h-64 overflow-y-auto w-80 max-w-[calc(100vw-2rem)] ${getDropdownPosition()}`}>
                                {/* Header with clear all button */}
                                <div className="sticky top-0 bg-white border-b border-gray-200 p-2 flex items-center justify-between">
                                    <span className="text-xs font-medium text-gray-700">Select Types</span>
                                    {filters.violationTypes.length > 0 && (
                                        <button
                                            onClick={() => setFilters(prev => ({ ...prev, violationTypes: [] }))}
                                            className="text-xs text-blue-600 hover:text-blue-800 hover:underline"
                                        >
                                            Clear All
                                        </button>
                                    )}
                                </div>

                                {/* Violation types list */}
                                {isLoadingViolationTypes ? (
                                    <div className="px-3 py-4 text-xs text-gray-500 text-center">
                                        Loading violation types...
                                    </div>
                                ) : violationTypesError ? (
                                    <div className="px-3 py-2 text-xs text-red-600">
                                        <div>Error loading types</div>
                                        {violationTypesError.includes('Network Error') && (
                                            <div className="text-xs text-gray-500 mt-1">
                                                CORS/Network issue detected
                                            </div>
                                        )}
                                        {onRetryViolationTypes && (
                                            <button 
                                                onClick={(e) => {
                                                    e.preventDefault();
                                                    e.stopPropagation();
                                                    onRetryViolationTypes();
                                                }}
                                                className="text-blue-600 hover:underline"
                                            >
                                                Retry
                                            </button>
                                        )}
                                    </div>
                                ) : (Array.isArray(violationTypes) && violationTypes.length > 0) || (typeof violationTypes === 'object' && violationTypes !== null && Object.keys(violationTypes).length > 0) ? (
                                    // Handle both flat array and category-based structures
                                    (() => {
                                        if (Array.isArray(violationTypes)) {
                                            // Flat array structure
                                            return violationTypes.map((violationType, index) => {
                                                const value = typeof violationType === 'object' ? violationType.name || violationType.value : violationType;
                                                const label = typeof violationType === 'object' ? violationType.name || violationType.label || violationType.value : violationType;
                                                const isSelected = filters.violationTypes.includes(value);
                                                
                                                return (
                                                    <button
                                                        key={`flat-${index}`}
                                                        onClick={() => {
                                                            if (isSelected) {
                                                                setFilters(prev => ({
                                                                    ...prev,
                                                                    violationTypes: prev.violationTypes.filter(type => type !== value)
                                                                }));
                                                            } else {
                                                                setFilters(prev => ({
                                                                    ...prev,
                                                                    violationTypes: [...prev.violationTypes, value]
                                                                }));
                                                            }
                                                        }}
                                                        className={`w-full text-left px-3 py-2 text-xs cursor-pointer hover:bg-gray-50 transition-colors ${
                                                            isSelected ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-700'
                                                        }`}
                                                    >
                                                        {label}
                                                    </button>
                                                );
                                            });
                                        } else if (typeof violationTypes === 'object' && violationTypes !== null) {
                                            // Category-based structure
                                            return Object.entries(violationTypes).map(([category, violations]) => (
                                                <div key={category}>
                                                    {/* Category Header */}
                                                    <div className="px-3 py-2 text-xs font-semibold text-gray-700 bg-gray-100 border-b border-gray-200">
                                                        {category}
                                                    </div>
                                                    {/* Violation Types in this category */}
                                                    {Array.isArray(violations) ? violations.map((violation, index) => {
                                                        const isSelected = filters.violationTypes.includes(violation);
                                                        return (
                                                            <button
                                                                key={`${category}-${index}`}
                                                                onClick={() => {
                                                                    if (isSelected) {
                                                                        setFilters(prev => ({
                                                                            ...prev,
                                                                            violationTypes: prev.violationTypes.filter(type => type !== violation)
                                                                        }));
                                                                    } else {
                                                                        setFilters(prev => ({
                                                                            ...prev,
                                                                            violationTypes: [...prev.violationTypes, violation]
                                                                        }));
                                                                    }
                                                                }}
                                                                className={`w-full text-left px-3 py-2 text-xs cursor-pointer hover:bg-gray-50 transition-colors pl-6 ${
                                                                    isSelected ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-700'
                                                                }`}
                                                            >
                                                                {violation}
                                                            </button>
                                                        );
                                                    }) : (
                                                        <button
                                                            key={`${category}-single`}
                                                            onClick={() => {
                                                                if (filters.violationTypes.includes(violations)) {
                                                                    setFilters(prev => ({
                                                                        ...prev,
                                                                        violationTypes: prev.violationTypes.filter(type => type !== violations)
                                                                    }));
                                                                } else {
                                                                    setFilters(prev => ({
                                                                        ...prev,
                                                                        violationTypes: [...prev.violationTypes, violations]
                                                                    }));
                                                                }
                                                            }}
                                                            className={`w-full text-left px-3 py-2 text-xs cursor-pointer hover:bg-gray-50 transition-colors pl-6 ${
                                                                filters.violationTypes.includes(violations) ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-700'
                                                            }`}
                                                        >
                                                            {violations}
                                                        </button>
                                                    )}
                                                </div>
                                            ));
                                        } else {
                                            return <div className="px-3 py-4 text-xs text-gray-500 text-center">No Data Available</div>;
                                        }
                                    })()
                                ) : (
                                    <div className="px-3 py-4 text-xs text-gray-500 text-center">No Data Available</div>
                                )}
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}