import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { isWithinInterval, format } from 'date-fns';
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";

import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";

import api from '../lib/api';
import { ViolationPieChart, StatusPieChart } from '@/components/ui/Charts';
import { ViolationFilters } from '@/components/ViolationFilters';
import { ViolationList } from '@/components/ViolationList';
import { SharedSidebar } from '@/components/ui/SharedSidebar';
import { SharedHeader } from '@/components/ui/SharedHeader';
import { SharedFooter } from '@/components/ui/SharedFooter';

import { DateRangePicker } from '@/components/ui/DateRangePicker';
import { Users } from 'lucide-react';
import { getImagePath } from '../lib/utils';

export function DashboardPage() {
    const navigate = useNavigate();
    const location = useLocation();

    // State for the master list of violations and the selected one
    const [violations, setViolations] = useState([]);
    const [selectedViolation, setSelectedViolation] = useState(null);
    const [isLoadingViolationDetails, setIsLoadingViolationDetails] = useState(false);

    const [isLoading, setIsLoading] = useState(true);

    
    // State for API response data
    const [apiData, setApiData] = useState({
        violations: [],
        counts: {
            total_count: 0,
            new_count: 0,
            raised_count: 0,
            rejected_count: 0
        },
        pagination: {
            current_page: 1,
            page_size: 20,
            total_items: 0,
            total_pages: 0,
            has_next: false,
            has_prev: false
        }
    });

    // State for total counts (unfiltered) - these should not change when filters are applied
    const [totalCounts, setTotalCounts] = useState({
        total_count: 0,
        new_count: 0,
        raised_count: 0,
        rejected_count: 0
    });

    // State for statistics data for pie charts
    const [statistics, setStatistics] = useState({
        violationTypes: [],
        categories: {},
        statusCounts: {
            new: 0,
            raised: 0,
            rejected: 0
        }
    });

    // State for user menu
    const [showUserMenu, setShowUserMenu] = useState(false);
    
    // State for sidebar toggle
    const [showSidebar, setShowSidebar] = useState(true);
    
    // State for mobile menu
    const [showMobileMenu, setShowMobileMenu] = useState(false);
    
    // State for violation types dropdown
    const [showViolationTypesDropdown, setShowViolationTypesDropdown] = useState(false);
    
    // Ref for violation types container
    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';
    };

    // State for violation types from API
    const [violationTypes, setViolationTypes] = useState([]);
    const [isLoadingViolationTypes, setIsLoadingViolationTypes] = useState(false);
    const [violationTypesError, setViolationTypesError] = useState(null);
    
    // Ref to track if violation types have been fetched
    const hasFetchedViolationTypes = useRef(false);

    // State for filters
    const [filters, setFilters] = useState({
        search: '',
        status: 'all',
        violationTypes: [], // Changed from violationType to violationTypes array
        dateRange: { 
            from: (() => {
                const today = new Date();
                const thirtyDaysAgo = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 29);
                return thirtyDaysAgo;
            })(), // 30 days ago (inclusive)
            to: new Date() // today
        }
    });

    // Separate date range for overview statistics (independent from list filters)
    // Default to 30 days period
    const [overviewDateRange, setOverviewDateRange] = useState(() => {
        const today = new Date();
        const thirtyDaysAgo = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 29);
        return {
            from: thirtyDaysAgo, // 30 days ago (inclusive)
            to: today // today
        };
    });

    // State for pagination
    const [currentPage, setCurrentPage] = useState(1);
    const recordsPerPage = apiData.pagination.page_size || 20;

    // Debug function to log date calculations
    const debugDateCalculation = (range, period) => {
        if (range?.from && range?.to) {
            const fromDateStart = new Date(range.from.getFullYear(), range.from.getMonth(), range.from.getDate());
            const toDateStart = new Date(range.to.getFullYear(), range.to.getMonth(), range.to.getDate());
            const diffTime = toDateStart - fromDateStart;
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
            
            console.log('🔍 Date Calculation Debug:', {
                originalFrom: range.from.toISOString(),
                originalTo: range.to.toISOString(),
                fromDateStart: fromDateStart.toISOString(),
                toDateStart: toDateStart.toISOString(),
                fromDateFormatted: format(range.from, 'yyyy-MM-dd'),
                toDateFormatted: format(range.to, 'yyyy-MM-dd'),
                diffTime: diffTime,
                diffDays,
                calculatedPeriod: period,
                isToday: range.from.toDateString() === new Date().toDateString() && 
                        range.to.toDateString() === new Date().toDateString(),
                is6Months: diffDays >= 180 && diffDays <= 184,
                is1Year: diffDays >= 365 && diffDays <= 366
            });
        }
    };

    // Fetch statistics data for pie charts
    const fetchStatistics = useCallback(async (dateRange = null) => {
        try {
            // Use overviewDateRange if no dateRange is provided
            const range = dateRange || overviewDateRange;
            
            // Check if today's date is selected
            const today = new Date();
            const isToday = range?.from && range?.to && 
                range.from.toDateString() === today.toDateString() && 
                range.to.toDateString() === today.toDateString();
            
            // Determine period and parameters
            let period = '30 days'; // Default period
            let params = new URLSearchParams({
                include_categories: 'true'
            });
            
            if (isToday) {
                // If today's date is selected, send "today" as period
                period = 'today';
                params.append('period', period);
            } else if (range?.from && range?.to) {
                // Calculate period based on date range filter
                const fromDate = range.from;
                const toDate = range.to;
                
                // Calculate the actual number of days between dates (inclusive)
                // Reset time to start of day for accurate calculation
                const fromDateStart = new Date(fromDate.getFullYear(), fromDate.getMonth(), fromDate.getDate());
                const toDateStart = new Date(toDate.getFullYear(), toDate.getMonth(), toDate.getDate());
                const diffTime = toDateStart - fromDateStart;
                const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1; // +1 for inclusive calculation
                
                // Additional debugging for the specific case
                console.log('🔢 Raw calculation:', {
                    fromDate: fromDate.toISOString(),
                    toDate: toDate.toISOString(),
                    fromDateStart: fromDateStart.toISOString(),
                    toDateStart: toDateStart.toISOString(),
                    diffTime: diffTime,
                    diffDays: diffDays,
                    diffTimeInDays: diffTime / (1000 * 60 * 60 * 24)
                });
                
                // Map the calculated days to the correct period
                // First, try to detect if this matches a specific preset
                let detectedPeriod = null;
                
                // Check if this matches "Last 6 months" preset (approximately 180-184 days)
                if (diffDays >= 180 && diffDays <= 184) {
                    detectedPeriod = '6 months';
                    console.log('🎯 Detected 6 months period:', { diffDays, detectedPeriod });
                }
                // Special case: Check for the exact date range from screenshot (March 2 to Sept 2, 2025)
                else if (format(range.from, 'yyyy-MM-dd') === '2025-03-02' && format(range.to, 'yyyy-MM-dd') === '2025-09-02') {
                    detectedPeriod = '6 months';
                    console.log('🎯 Special case: March-Sept 2025 detected as 6 months:', { diffDays, detectedPeriod });
                }
                // Check if this matches "Last 1 year" preset (approximately 365-366 days)
                else if (diffDays >= 365 && diffDays <= 366) {
                    detectedPeriod = '1 year';
                    console.log('🎯 Detected 1 year period:', { diffDays, detectedPeriod });
                }
                
                if (detectedPeriod) {
                    period = detectedPeriod;
                    console.log('✅ Using detected period:', period);
                } else {
                    // Fallback to day-based mapping
                    console.log('⚠️ Using fallback logic for diffDays:', diffDays);
                    if (diffDays === 1) period = '1 day';
                    else if (diffDays === 2) period = '2 days';
                    else if (diffDays <= 7) period = '7 days';
                    else if (diffDays <= 30) period = '30 days';
                    else if (diffDays <= 90) period = '90 days';
                    else if (diffDays <= 184) period = '6 months'; // 6 months can be 180-184 days
                    else period = '1 year';
                    console.log('📊 Fallback period assigned:', period);
                }
                
                // Debug the calculation after period is determined
                debugDateCalculation(range, period);
                
                params.append('period', period);
                
                // Add date range parameters for non-today periods
                // Format dates as YYYY-MM-DD to avoid timezone issues
                const fromDateFormatted = format(range.from, 'yyyy-MM-dd');
                const toDateFormatted = format(range.to, 'yyyy-MM-dd');
                params.append('from_date', fromDateFormatted);
                params.append('to_date', toDateFormatted);
            } else {
                // Default period
                params.append('period', period);
            }
            
            const response = await api.get(`/violations/statistics/?${params.toString()}`);
            
            if (response.data) {
                // Transform the API response to match our chart data structure
                const categories = response.data.categories || {};
                const summary = response.data.summary || {};
                
                // Extract violation types from categories
                const violationTypes = [];
                Object.entries(categories).forEach(([categoryName, categoryData]) => {
                    if (categoryData.count > 0) {
                        // Add only category-level data (not individual violations)
                        violationTypes.push({
                            category: categoryName,
                            count: categoryData.count
                        });
                    }
                });
                
                setStatistics({
                    violationTypes: violationTypes,
                    categories: response.data.categories || {},
                    statusCounts: {
                        new: summary.new_count || 0,
                        raised: summary.raised_count || 0,
                        rejected: summary.rejected_count || 0
                    },
                    summary: summary,
                    period: response.data.period,
                    currentPeriod: response.data.current_period,
                    comparison: response.data.comparison
                });
            }
        } catch (err) {
            // Fallback to empty statistics
            setStatistics({
                violationTypes: [],
                categories: {},
                statusCounts: { new: 0, raised: 0, rejected: 0 }
            });
        }
    }, []); // Removed overviewDateRange dependency since it's passed as parameter

    // Fetch violation types from API
    const fetchViolationTypes = async () => {
        // Prevent multiple simultaneous calls or if already fetched
        if (isLoadingViolationTypes || hasFetchedViolationTypes.current) {
            return;
        }
        
        setIsLoadingViolationTypes(true);
        try {
            // Use the configured API instance with proper base URL and interceptors
            const response = await api.get('/violation-types/');
            
            const data = response.data;
            
            // Ensure we have valid data
            if (data && (Array.isArray(data) || typeof data === 'object')) {
                setViolationTypes(data);
                hasFetchedViolationTypes.current = true; // Mark as fetched
            } else {
                console.warn('Invalid violation types data received:', data);
                setViolationTypes([]);
            }
            setViolationTypesError(null); // Clear any previous errors
        } catch (error) {
            console.error('Error fetching violation types:', error);
            console.error('Error details:', {
                message: error.message,
                code: error.code,
                status: error.status
            });
            setViolationTypesError(error.message || 'Failed to fetch violation types');
            
            // Handle specific error types
            if (error.message === 'Network Error' || error.message.includes('Failed to fetch')) {
                console.warn('Network error - this might be a CORS issue or server unavailable');
                // Use fallback violation types from existing violations
                const fallbackTypes = extractViolationTypesFromViolations();
                if (fallbackTypes.length > 0) {
                    setViolationTypes(fallbackTypes);
                    setViolationTypesError('Using cached violation types (API unavailable)');
                    hasFetchedViolationTypes.current = true; // Mark as fetched even with fallback
                }
            }
            if (violationTypes.length === 0) {
                setViolationTypes([]);
            }
        } finally {
            setIsLoadingViolationTypes(false);
        }
    };

    // Extract violation types from existing violations as fallback
    const extractViolationTypesFromViolations = () => {
        if (!Array.isArray(violations) || violations.length === 0) return [];
        
        const types = new Set();
        violations.forEach(v => {
            if (v.violation_types) {
                try {
                    const parsed = JSON.parse(v.violation_types || '[]');
                    const violationTypes = Array.isArray(parsed) ? parsed : [parsed];
                    violationTypes.forEach(type => {
                        if (type && type.trim() !== '') {
                            types.add(type.replace(/\\"/g, '"').trim());
                        }
                    });
                } catch (error) {
                    // Handle parsing error silently
                }
            }
        });
        
        return Array.from(types).map(type => ({ name: type }));
    };

    // Fetch violations with date range support
    const fetchViolations = useCallback(async (dateRange = null) => {
        setIsLoading(true);
        try {
            // Use provided date range or fall back to filters
            const range = dateRange || filters.dateRange;
            let url = '/violations/';
            const params = new URLSearchParams();
            
            // Add date range parameters - API expects YYYY-MM-DD format
            if (range?.from) {
                const fromDate = format(range.from, 'yyyy-MM-dd'); // Format as YYYY-MM-DD preserving local date
                params.append('start_date', fromDate);
            }
            if (range?.to) {
                const toDate = format(range.to, 'yyyy-MM-dd'); // Format as YYYY-MM-DD preserving local date
                params.append('end_date', toDate);
            }
            
            // Add status filter - API uses 'challan_status' parameter
            if (filters.status !== 'all') {
                params.append('challan_status', filters.status);
            }
            
            // Add violation type filter - support multiple types
            if (filters.violationTypes.length > 0) {
                filters.violationTypes.forEach(type => {
                    params.append('violation_type', type);
                });
            }
            
            // Add search filter
            if (filters.search.trim()) {
                params.append('search', filters.search.trim());
            }
            
            // Add pagination
            params.append('page', currentPage.toString());
            
            if (params.toString()) {
                url += `?${params.toString()}`;
            }
            
            const response = await api.get(url);
            
            // Handle the API response structure
            const violationsData = response.data?.violations || [];
            const countsData = response.data?.counts || {
                total_count: 0,
                new_count: 0,
                raised_count: 0,
                rejected_count: 0
            };
            const paginationData = response.data?.pagination || {
                current_page: 1,
                page_size: 20,
                total_items: 0,
                total_pages: 0,
                has_next: false,
                has_prev: false
            };
            
            setViolations(violationsData);
            setApiData({
                violations: violationsData,
                counts: countsData,
                pagination: paginationData
            });

            // Set total counts only when no filters are applied (initial load or when filters are reset)
            const hasActiveFilters = filters.status !== 'all' || 
                                   filters.violationTypes.length > 0 || 
                                   filters.search.trim() || 
                                   (filters.dateRange?.from && filters.dateRange?.to);
            
            if (!hasActiveFilters) {
                setTotalCounts(countsData);
            }
        } catch (err) {
            // Handle error silently or add proper error handling
            setViolations([]); // Ensure we always have an array
        } finally {
            setIsLoading(false);
        }
    }, [filters.status, filters.violationTypes, filters.search, currentPage]); // Removed filters.dateRange from dependencies

    // Consolidated useEffect for initial data loading
    useEffect(() => {
        // Fetch all data once when component mounts
        fetchViolations(filters.dateRange);
        fetchStatistics(overviewDateRange);
        
        // Fetch violation types only if not already fetched
        if (!hasFetchedViolationTypes.current && !isLoadingViolationTypes) {
            fetchViolationTypes();
        }
    }, []); // Empty dependency array - only run once on mount

    // Fetch total counts (unfiltered) on component mount
    useEffect(() => {
        const fetchTotalCounts = async () => {
            try {
                // Fetch violations without any filters to get total counts
                const response = await api.get('/violations/');
                const countsData = response.data?.counts || {
                    total_count: 0,
                    new_count: 0,
                    raised_count: 0,
                    rejected_count: 0
                };
                setTotalCounts(countsData);
            } catch (error) {
                console.error('Error fetching total counts:', error);
            }
        };
        
        fetchTotalCounts();
    }, []); // Empty dependency array - only run once on mount

    // Handle clicks outside user menu to close it
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (showUserMenu && !event.target.closest('.user-menu-container')) {
                setShowUserMenu(false);
            }
        };

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

    // 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]);

    // Refetch statistics when overview date range changes (for charts only)
    useEffect(() => {
        if (overviewDateRange?.from || overviewDateRange?.to) {
            fetchStatistics(overviewDateRange);
        }
    }, [overviewDateRange]); // Removed fetchStatistics from dependencies

    // Refetch violations when filters change
    useEffect(() => {
        fetchViolations(filters.dateRange);
    }, [filters.dateRange, filters.status, filters.violationTypes, filters.search]); // Removed fetchViolations from dependencies

    // Handle refresh parameter from URL
    useEffect(() => {
        const searchParams = new URLSearchParams(location.search);
        if (searchParams.get('refresh') === 'true') {
            // Refresh dashboard data
            fetchViolations(filters.dateRange);
            fetchStatistics(overviewDateRange);
            // Remove the refresh parameter from URL
            navigate('/dashboard', { replace: true });
        }
    }, [location.search, navigate, filters.dateRange, overviewDateRange]); // Removed fetchViolations and fetchStatistics from dependencies

    // Memoized filtering logic
    const filteredViolations = useMemo(() => {
        // Ensure violations is always an array
        if (!Array.isArray(violations)) {
            return [];
        }
        
        return violations.filter(v => {
            const searchLower = filters.search.toLowerCase();

            // Search filter
            const matchesSearch = filters.search === '' ||
                v.license_plate_number?.toLowerCase().includes(searchLower) ||
                v.location_text?.toLowerCase().includes(searchLower) ||
                v.junction_name?.toLowerCase().includes(searchLower) ||
                v.police_station?.toLowerCase().includes(searchLower);

            // Status filter
            const matchesStatus = filters.status === 'all' || v.challan_status === filters.status;

            // Violation type filter - support multiple types
            let violationTypes;
            try {
                const parsed = JSON.parse(v.violation_types || '[]');
                violationTypes = Array.isArray(parsed) ? parsed : [parsed];
                // Clean up escaped quotes for comparison
                violationTypes = violationTypes.map(type => type.replace(/\\"/g, '"').trim());
            } catch (error) {
                violationTypes = [];
            }
            
            // If no violation types are selected, show all
            const matchesViolationType = filters.violationTypes.length === 0 || 
                filters.violationTypes.some(selectedType => 
                    violationTypes.filter(type => type && type.trim() !== '').includes(selectedType)
                );

            // Skip date range filtering since API handles it
            // The API should return only violations within the specified date range
            const result = matchesSearch && matchesStatus && matchesViolationType;
            
            return result;
        });
    }, [violations, filters.search, filters.status, filters.violationTypes]); // Removed filters.dateRange dependency

    // Pagination logic - use API pagination data
    const totalPages = apiData.pagination.total_pages || 1;
    const totalItems = apiData.pagination.total_items || filteredViolations.length;
    
    // For now, we'll use the current page violations from API
    // In the future, you can implement server-side pagination
    const currentViolations = filteredViolations;

    // Reset to first page when filters change
    useEffect(() => {
        setCurrentPage(1);
    }, [filters.dateRange, filters.status, filters.violationTypes, filters.search]); // Only reset page, don't fetch data

    // Calculate statistics
    const stats = useMemo(() => {
        // Use statistics API summary data if available, otherwise fall back to API counts
        const total = statistics.summary?.total_violations || apiData.counts.total_count || violations.length;
        const newCount = statistics.statusCounts.new || apiData.counts.new_count || (Array.isArray(violations) ? violations.filter(v => v.challan_status === 'New').length : 0);
        const raisedCount = statistics.statusCounts.raised || apiData.counts.raised_count || (Array.isArray(violations) ? violations.filter(v => v.challan_status === 'Raised').length : 0);
        const rejectedCount = statistics.statusCounts.rejected || apiData.counts.rejected_count || (Array.isArray(violations) ? violations.filter(v => v.challan_status === 'Rejected').length : 0);

        // Calculate percentage change from statistics API comparison data
        // If no comparison data available, show 0% change
        const percentageChange = statistics.comparison?.percentage_changes?.total_violations || 0;

        return {
            total,
            newCount,
            raisedCount,
            rejectedCount,
            percentageChange
        };
    }, [statistics]);

    // Process violation types for pie chart from statistics API data
    const violationTypesForChart = useMemo(() => {
        // Use statistics data from the API instead of processing violations list
        if (statistics.categories && Object.keys(statistics.categories).length > 0) {
            // Transform the categories data to match chart format
            const chartData = [];
            
            Object.entries(statistics.categories).forEach(([categoryName, categoryData]) => {
                if (categoryData.count > 0) {
                    // Add category-level data
                    chartData.push({
                        category: categoryName,
                        count: categoryData.count
                    });
                }
            });
            
            // Sort by count (highest first) and return
            const sortedData = chartData.sort((a, b) => b.count - a.count);
            return sortedData;
        }
        
        // Fallback: Create default categories for common traffic violations
        const fallbackCategories = {
            'Signal Jumping': 'Traffic Signal Violations',
            'Red Light Violation': 'Traffic Signal Violations',
            'Stop Sign Violation': 'Traffic Signal Violations',
            'Triple Riding': 'Passenger Violations',
            'Extra Passengers': 'Passenger Violations',
            'Overloading': 'Passenger Violations',
            'No Helmet': 'Safety Equipment Violations',
            'No Seat Belt': 'Safety Equipment Violations',
            'Speeding': 'Speed Violations',
            'Overspeeding': 'Speed Violations',
            'Rash Driving': 'Dangerous Driving',
            'Drunk Driving': 'Dangerous Driving',
            'Wrong Side Driving': 'Lane Violations',
            'Illegal Parking': 'Parking Violations',
            'No Parking': 'Parking Violations'
        };
        
        // Return empty array if no statistics data
        return [];
    }, [statistics.categories]);

    const handleLogout = () => {
        localStorage.removeItem('accessToken');
        navigate('/login');
    };

    const handleSelectViolation = async (violation) => {
        setIsLoadingViolationDetails(true);
        try {
            // Fetch detailed violation data from API
            const response = await api.get(`/violations/${violation.id}`);
            const detailedViolation = response.data;
            
            // Handle nested response structure and merge data
            const violationData = detailedViolation.violation || detailedViolation;
            const mergedData = {
                ...violationData,
                officer: detailedViolation.officer || violationData.officer,
                vehicle: detailedViolation.vehicle || violationData.vehicle,
                // Preserve the image data and junction_name from the original violation if the detailed API doesn't have it
                composite_image_path: violationData.composite_image_path || violation.composite_image_path,
                junction_name: violationData.junction_name || violation.junction_name
            };
            
            // Set the merged violation data
            setSelectedViolation(mergedData);
        } catch (error) {
            console.error('Failed to fetch violation details:', error);
            // Fallback to basic violation data if API fails
            setSelectedViolation({
                id: violation.id,
                license_plate_number: violation.license_plate_number,
                composite_image_path: violation.composite_image_path,
                junction_name: violation.junction_name,
                // Include other fields that might be needed
                device_id: violation.device_id,
                location_text: violation.location_text,
                violation_types: violation.violation_types,
                timestamp: violation.timestamp
            });
        } finally {
            setIsLoadingViolationDetails(false);
        }
    };

    const handleBackToList = async () => {
        setSelectedViolation(null);
        
        // Refresh dashboard data when returning to list to show updated counts
        try {
            await fetchViolations(filters.dateRange);
            await fetchStatistics(overviewDateRange);
        } catch (error) {
            console.error('Failed to refresh dashboard data:', error);
        }
    };

    const handleViolationUpdate = async (updatedViolation) => {
        // Update the local violation in the list
        setViolations(prev => prev.map(v => v.id === updatedViolation.id ? updatedViolation : v));
        
        // Refresh dashboard data to get updated counts and statistics
        try {
            await fetchViolations(filters.dateRange);
            await fetchStatistics(overviewDateRange);
        } catch (error) {
            console.error('Failed to refresh dashboard data:', error);
        }
    };

    // Navigate to next NEW violation in the list
    const handleNextViolation = async () => {
        if (selectedViolation && violations.length > 0) {
            const currentIndex = violations.findIndex(v => v.id === selectedViolation.id);
            
            // First, try to find the next NEW violation on the current page
            let nextNewViolation = null;
            for (let i = currentIndex + 1; i < violations.length; i++) {
                if (violations[i].challan_status?.toLowerCase() === 'new') {
                    nextNewViolation = violations[i];
                    break;
                }
            }
            
            if (nextNewViolation) {
                // Found next NEW violation on current page
                await handleSelectViolation(nextNewViolation);
            } else if (apiData.pagination.has_next) {
                // No more NEW violations on current page, try next page
                await handlePageChange(currentPage + 1).then(() => {
                    // After page change, find the first NEW violation
                    const firstNewViolation = violations.find(v => v.challan_status?.toLowerCase() === 'new');
                    if (firstNewViolation) {
                        handleSelectViolation(firstNewViolation);
                    } else {
                        // If no NEW violations on next page, go back to list
                        handleBackToList();
                    }
                });
            } else {
                // No more pages, go back to list
                handleBackToList();
            }
        }
    };







    // Pagination handlers
    const handlePageChange = async (page) => {
        try {
            setIsLoading(true);
            
            // Build URL with current filters and new page
            let url = '/violations/';
            const params = new URLSearchParams();
            
            // Add current filters
            if (filters.dateRange?.from) {
                const fromDate = format(filters.dateRange.from, 'yyyy-MM-dd');
                params.append('start_date', fromDate);
            }
            if (filters.dateRange?.to) {
                const toDate = format(filters.dateRange.to, 'yyyy-MM-dd');
                params.append('end_date', toDate);
            }
            
            if (filters.status !== 'all') {
                params.append('challan_status', filters.status);
            }
            
            if (filters.violationTypes.length > 0) {
                filters.violationTypes.forEach(type => {
                    params.append('violation_type', type);
                });
            }
            
            if (filters.search.trim()) {
                params.append('search', filters.search.trim());
            }
            
            // Add page parameter
            params.append('page', page.toString());
            
            if (params.toString()) {
                url += `?${params.toString()}`;
            }
            
            const response = await api.get(url);
            const violationsData = response.data?.violations || [];
            const countsData = response.data?.counts || apiData.counts;
            const paginationData = response.data?.pagination || apiData.pagination;
            
            setViolations(violationsData);
            setApiData({
                violations: violationsData,
                counts: countsData,
                pagination: paginationData
            });
            setCurrentPage(page);
        } catch (err) {
            // Handle error silently or add proper error handling
        } finally {
            setIsLoading(false);
        }
    };

    const handlePreviousPage = async () => {
        if (apiData.pagination.has_prev) {
            await handlePageChange(apiData.pagination.current_page - 1);
        }
    };

    const handleNextPage = async () => {
        if (apiData.pagination.has_next) {
            await handlePageChange(apiData.pagination.current_page + 1);
        }
    };

    const getStatusBadge = (status) => {
        switch (status?.toLowerCase()) {
            case 'raised': return <Badge className="bg-green-100 text-green-800 border-green-200 hover:bg-green-100 hover:text-green-800 hover:border-green-200">Raised</Badge>;
            case 'rejected': return <Badge className="bg-yellow-100 text-yellow-800 border-yellow-200 hover:bg-yellow-100 hover:text-yellow-800 hover:border-yellow-200">Rejected</Badge>;
            default: return <Badge className="bg-blue-100 text-blue-800 border-blue-200 hover:bg-blue-100 hover:text-blue-800 hover:border-blue-200">New</Badge>;
        }
    };

    const getViolationTypeBadge = (type) => {
        const lowerType = type.toLowerCase();
        if (lowerType.includes('helmet')) return <Badge className="bg-gray-100 text-gray-800 border-gray-200 mr-1 mb-1">{type}</Badge>;
        if (lowerType.includes('signal') || lowerType.includes('red light')) return <Badge className="bg-purple-100 text-purple-800 border-purple-200 mr-1 mb-1">{type}</Badge>;
        return <Badge className="bg-gray-100 text-gray-800 border-gray-200 mr-1 mb-1">{type}</Badge>;
    };



    // Handle navigation when violation is selected
    useEffect(() => {
        if (selectedViolation) {
            // Navigate to the violation detail page
            navigate(`/violation/${selectedViolation.id}`);
        }
    }, [selectedViolation, navigate]);

    return (
                <div className="flex h-screen bg-gray-50 overflow-hidden">
            {/* Responsive Sidebar */}
            <div className={`${showSidebar ? 'w-48 lg:w-48 md:w-40 sm:w-32 xs:w-24' : 'w-16 lg:w-16 md:w-12 sm:w-10 xs:w-8'} bg-white border-r border-gray-200 flex flex-col fixed left-0 top-20 lg:top-20 md:top-16 sm:top-12 xs:top-10 h-full z-30 transition-all duration-300`}>
                {/* Sidebar Toggle Button */}
                <div className="p-2 border-b border-gray-200">
                    <button 
                        onClick={() => setShowSidebar(!showSidebar)}
                        className="w-8 h-8 flex items-center justify-center text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-md transition-colors"
                    >
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d={showSidebar ? "M6 18L18 6M6 6l12 12" : "M4 6h16M4 12h16M4 18h16"} />
                        </svg>
                    </button>
                </div>

                <nav className="flex-1 p-4 space-y-2">
                    {/* Violations - Selected */}
                    <div className="flex items-center justify-between p-3 rounded-lg bg-blue-50 cursor-pointer hover:bg-blue-100 transition-colors">
                        <div className="flex items-center space-x-3">
                            <div className="w-5 h-5 flex items-center justify-center">
                                <svg className="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16" />
                                </svg>
                            </div>
                            {showSidebar && (
                                <span className="text-sm font-medium text-blue-700">Violations</span>
                            )}
                        </div>
                        {showSidebar && (
                            <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                        )}
                    </div>
                    
                    {/* Constables - Unselected */}
                    <div 
                        className="flex items-center justify-between p-3 rounded-lg bg-gray-50 cursor-pointer hover:bg-gray-100 transition-colors"
                        onClick={() => navigate('/constables')}
                    >
                        <div className="flex items-center space-x-3">
                            <div className="w-5 h-5 flex items-center justify-center">
                                <svg className="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                                </svg>
                            </div>
                            {showSidebar && (
                                <span className="text-sm font-medium text-gray-600">Constables</span>
                            )}
                        </div>
                    </div>
                </nav>
            </div>

            {/* Main Content Area - Responsive */}
                            <div className={`flex-1 flex flex-col transition-all duration-300 ${showSidebar ? 'ml-48 lg:ml-48 md:ml-40 sm:ml-32 xs:ml-24' : 'ml-16 lg:ml-16 md:ml-12 sm:ml-10 xs:ml-8'}`}>
                
                {/* Mobile Menu Overlay - Only visible on small screens */}
                {showMobileMenu && (
                    <div className="md:hidden sm:block fixed inset-0 bg-black bg-opacity-50 z-20">
                        <div className="fixed left-0 top-0 h-full w-64 bg-white shadow-lg transform transition-transform duration-300 ease-in-out">
                            <div className="p-4 border-b border-gray-200">
                                <div className="flex items-center justify-between">
                                    <h2 className="text-lg font-semibold text-gray-800">Menu</h2>
                                    <button 
                                        onClick={() => setShowMobileMenu(false)}
                                        className="w-8 h-8 flex items-center justify-center text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-md transition-colors"
                                    >
                                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                        </svg>
                                    </button>
                                </div>
                            </div>
                            <nav className="p-4 space-y-2">
                                <div className="flex items-center justify-between p-3 rounded-lg bg-blue-50 cursor-pointer hover:bg-blue-100 transition-colors">
                                    <div className="flex items-center space-x-3">
                                        <div className="w-5 h-5 flex items-center justify-center">
                                            <svg className="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 10h16M4 14h16M4 18h16" />
                                            </svg>
                                        </div>
                                        <span className="text-sm font-medium text-blue-700">Violations</span>
                                    </div>
                                    <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                                </div>
                                
                                <div 
                                    className="flex items-center justify-between p-3 rounded-lg bg-gray-50 cursor-pointer hover:bg-gray-100 transition-colors"
                                    onClick={() => {
                                        navigate('/constables');
                                        setShowMobileMenu(false);
                                    }}
                                >
                                    <div className="flex items-center space-x-3">
                                        <div className="w-5 h-5 flex items-center justify-center">
                                            <svg className="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
                                            </svg>
                                        </div>
                                        <span className="text-sm font-medium text-gray-600">Constables</span>
                                    </div>
                                </div>
                            </nav>
                        </div>
                    </div>
                )}
                {/* Full-width Header */}
                <header className="bg-white border-b border-gray-200 px-6 md:px-4 sm:px-3 py-2 md:py-2 sm:py-1 fixed top-0 left-0 right-0 z-20">
                    <div className="flex items-center justify-between">
                        {/* Left side - Logo and Heading */}
                        <div className="flex items-center space-x-6 lg:space-x-6 md:space-x-4 sm:space-x-3 xs:space-x-2">
                            <div className="flex items-center">
                                <img 
                                    src={getImagePath("pushpakAI-logo.svg")} 
                                    alt="PUSHPAK.AI" 
                                    className="h-14 w-[145px] lg:h-14 lg:w-[145px] md:h-12 md:w-[120px] sm:h-10 sm:w-[100px] xs:h-8 xs:w-[80px]"
                                    onError={(e) => {
                                        console.error('Logo failed to load:', e.target.src);
                                        // Try fallback path
                                        if (e.target.src !== '/image/pushpakAI-logo.svg') {
                                            e.target.src = '/image/pushpakAI-logo.svg';
                                        }
                                    }}
                                    onLoad={() => {
                                        console.log('Logo loaded successfully:', getImagePath("pushpakAI-logo.svg"));
                                    }}
                                />
                            </div>
                            <div className="border-l border-gray-300 h-12 lg:h-12 md:h-10 sm:h-8 xs:h-6"></div>
                            <div className="overview-section">
                                <h2 className="text-xl lg:text-xl md:text-lg sm:text-base xs:text-sm font-semibold text-gray-700">Overview</h2>
                            </div>
                        </div>
                        
                        {/* Right side - Date Range and User Menu */}
                        <div className="flex items-center space-x-4 md:space-x-3 sm:space-x-2">
                            <div className="date-range-section md:block sm:hidden">
                                <DateRangePicker
                                    value={overviewDateRange}
                                    onValueChange={(dateRange) => setOverviewDateRange(dateRange)}
                                    placeholder="Select time range"
                                    className="w-40 md:w-32 sm:w-28 h-10 md:h-9 sm:h-8 px-3 md:px-2 sm:px-2 py-2"
                                    hideCalendar={true}
                                />
                            </div>
                            
                            <div className="relative user-menu-container">
                                <button 
                                    onClick={() => setShowUserMenu(!showUserMenu)}
                                    className="w-12 h-12 lg:w-11 lg:h-11 md:w-10 md:h-10 sm:w-9 sm:h-9 xs:w-8 xs:h-8 rounded-full flex items-center justify-center hover:bg-gray-100 transition-colors cursor-pointer border-2 border-gray-200 hover:border-gray-300"
                                >
                                    <img 
                                        src={getImagePath("user-circle-icon.svg")} 
                                        alt="User" 
                                        className="w-10 h-10 lg:w-9 lg:h-9 md:w-8 md:h-8 sm:w-7 sm:h-7 xs:w-6 xs:h-6"
                                        onError={(e) => {
                                            console.error('User icon failed to load:', e.target.src);
                                            // Try fallback path
                                            if (e.target.src !== '/image/user-circle-icon.svg') {
                                                e.target.src = '/image/user-circle-icon.svg';
                                            }
                                        }}
                                        onLoad={() => {
                                            console.log('User icon loaded successfully:', getImagePath("user-circle-icon.svg"));
                                        }}
                                    />
                                </button>
                                
                                {/* User Dropdown Menu */}
                                {showUserMenu && (
                                    <div className="absolute right-0 mt-2 w-48 md:w-40 sm:w-36 bg-white rounded-md shadow-lg border border-gray-200 z-20">
                                        <div className="py-1">
                                            <button
                                                onClick={handleLogout}
                                                className="w-full text-left px-4 md:px-3 sm:px-2 py-2 md:py-1.5 sm:py-1 text-sm md:text-sm sm:text-xs text-gray-700 hover:bg-gray-100 transition-colors flex items-center gap-2"
                                            >
                                                <svg className="w-4 h-4 md:w-3.5 md:h-3.5 sm:w-3 sm:h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                                                </svg>
                                                Logout
                                            </button>
                                        </div>
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>
                </header>

                                                 {/* Responsive Dashboard Content */}
                <div className="flex-1 mt-20 lg:mt-20 md:mt-16 sm:mt-12 xs:mt-10 overflow-y-auto bg-white">
                    <div className="p-4 md:p-4 sm:p-3 space-y-4 md:space-y-4 sm:space-y-3 max-w-full">

                        {/* Stats and Charts Section - Responsive Grid */}
                        {/* This section shows overview statistics based on the overview date range picker */}
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-12 gap-4 md:gap-3 sm:gap-2">
                            {/* Violations Count - Responsive sizing */}
                            <div className="sm:col-span-1 lg:col-span-3">
                                <div className="bg-white rounded-lg border border-gray-200 p-4 md:p-4 sm:p-3 h-full">
                                    <h4 className="text-xs text-gray-600 mb-2 md:mb-2 sm:mb-1">Violations</h4>
                                    <div className="w-full h-48 lg:h-60 md:h-56 sm:h-40 flex items-center justify-center">
                                        {statistics.summary?.total_violations > 0 ? (
                                            <div className="text-center flex flex-col justify-center items-center">
                                                <p className="text-2xl md:text-xl sm:text-lg font-bold text-black mb-1">{statistics.summary.total_violations}</p>
                                                <div className={`text-xs flex justify-center items-center gap-1 ${stats.percentageChange >= 0 ? 'text-green-600' : 'text-red-600'}`}>
                                                    <img 
                                                        src={stats.percentageChange >= 0 ? getImagePath("arrow-up.svg") : getImagePath("down-arrow-icon.svg")} 
                                                        alt={stats.percentageChange >= 0 ? "↑" : "↓"} 
                                                        className="w-3 h-3 md:w-3 md:h-3 sm:w-2.5 sm:h-2.5" 
                                                    />
                                                    <span>{Math.abs(stats.percentageChange).toFixed(1)}%</span>
                                                </div>
                                            </div>
                                        ) : (
                                            <div className="text-center text-gray-500">
                                                <p className="text-sm font-medium">
                                                    {statistics.summary ? 'No Data Available' : 'Loading...'}
                                                </p>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Violation Breakdown Donut Chart - Responsive sizing */}
                            <div className="sm:col-span-1 lg:col-span-4">
                                <div className="bg-white rounded-lg border border-gray-200 p-4 md:p-4 sm:p-3 h-full">
                                    <h4 className="text-xs text-gray-600 mb-1">Violation breakdown</h4>
                                    <div className="w-full h-48 lg:h-60 md:h-56 sm:h-40 flex items-center justify-center">
                                        {violationTypesForChart && violationTypesForChart.length > 0 ? (
                                            <ViolationPieChart data={violationTypesForChart} />
                                        ) : (
                                            <div className="text-center text-gray-500">
                                                <p className="text-sm font-medium">
                                                    {statistics.categories ? 'No Data Available' : 'Loading...'}
                                                </p>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Status Donut Chart - Responsive sizing */}
                            <div className="sm:col-span-1 lg:col-span-5">
                                <div className="bg-white rounded-lg border border-gray-200 p-4 md:p-4 sm:p-3 h-full">
                                    <h4 className="text-xs text-gray-600 mb-1">Status</h4>
                                    <div className="w-full h-48 lg:h-60 md:h-56 sm:h-40 flex items-center justify-center">
                                        {(statistics.statusCounts.new > 0 || statistics.statusCounts.raised > 0 || statistics.statusCounts.rejected > 0) ? (
                                            <StatusPieChart
                                                newCount={statistics.statusCounts.new || 0}
                                                raisedCount={statistics.statusCounts.raised || 0}
                                                rejectedCount={statistics.statusCounts.rejected || 0}
                                            />
                                        ) : (
                                            <div className="text-center text-gray-500">
                                                <p className="text-sm font-medium">
                                                    {statistics.statusCounts ? 'No Data Available' : 'Loading...'}
                                                </p>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            </div>
                        </div>

                    {/* Horizontal Divider */}
                    <div className="border-t border-gray-200 my-4"></div>

                    {/* Table Section - This section shows violations based on table filters, independent of overview date range */}
                    {/* Responsive Status Tabs and Filters */}
                    <div className="w-full space-y-4">
                        {/* Status Tabs - Responsive */}
                        {/* These tabs show counts from the current table data, not from overview statistics */}
                        <div className="flex flex-wrap gap-2 bg-white rounded-lg p-2 overflow-x-auto">
                            <button
                                onClick={() => setFilters(prev => ({ ...prev, status: 'all' }))}
                                className={`py-2 px-4 rounded-md text-xs font-medium transition-colors whitespace-nowrap ${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 bg-purple-100 text-purple-600 px-2 py-1 rounded-full text-xs">
                                    {totalCounts.total_count > 0 ? totalCounts.total_count : 'No Data'}
                                </span>
                            </button>
                            <button
                                onClick={() => setFilters(prev => ({ ...prev, status: 'New' }))}
                                className={`py-2 px-4 rounded-md text-xs font-medium transition-colors whitespace-nowrap ${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 bg-blue-100 text-blue-800 px-2 py-1 rounded-full text-xs">
                                    {totalCounts.new_count > 0 ? totalCounts.new_count : 'No Data'}
                                </span>
                            </button>
                            <button
                                onClick={() => setFilters(prev => ({ ...prev, status: 'Raised' }))}
                                className={`py-2 px-4 rounded-md text-xs font-medium transition-colors whitespace-nowrap ${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 bg-green-100 text-green-600 px-2 py-1 rounded-full text-xs">
                                    {totalCounts.raised_count > 0 ? totalCounts.raised_count : 'No Data'}
                                </span>
                            </button>
                            <button
                                onClick={() => setFilters(prev => ({ ...prev, status: 'Rejected' }))}
                                className={`py-2 px-4 rounded-md text-xs font-medium transition-colors whitespace-nowrap ${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 bg-yellow-100 text-yellow-600 px-2 py-1 rounded-full text-xs">
                                    {totalCounts.rejected_count > 0 ? totalCounts.rejected_count : 'No Data'}
                                </span>
                            </button>
                        </div>

                        {/* Search and Filter Dropdowns - Single Line Layout */}
                        <div className="flex flex-wrap items-end gap-3 w-full">
                            <div className="flex-1 min-w-[200px]">
                                <label className="block text-xs text-gray-600 mb-1">Search</label>
                                <Input
                                    placeholder="Search by ID/license plate"
                                    value={filters.search}
                                    onChange={(e) => setFilters(prev => ({ ...prev, search: e.target.value }))}
                                    className="text-sm w-full h-10"
                                />
                            </div>

                            <div className="flex-1 min-w-[200px]">
                                <label className="block text-xs text-gray-600 mb-1">Time Range</label>
                                <DateRangePicker
                                    value={filters.dateRange}
                                    onValueChange={(dateRange) => setFilters(prev => ({ ...prev, dateRange }))}
                                    placeholder="Select time range"
                                    className="w-full h-10 px-3 py-2 text-sm"
                                />
                            </div>

                            <div className="flex-1 min-w-[200px] 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 py-2 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 h-10"
                                    >
                                        <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 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>
                                                    )}
                                                    <button 
                                                        onClick={(e) => {
                                                            e.preventDefault();
                                                            e.stopPropagation();
                                                            setViolationTypesError(null);
                                                            fetchViolationTypes();
                                                        }}
                                                        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>

                    {/* Horizontal Divider */}
                    <div className="border-t border-gray-200 my-4"></div>

                    {/* Violations Table */}
                    <div className="w-full overflow-x-auto border border-gray-200 rounded-lg" style={{ minWidth: 'fit-content' }}>
                        {isLoadingViolationDetails && (
                            <div className="mb-2 p-2 bg-blue-50 border border-blue-200 rounded-md">
                                <div className="flex items-center space-x-2 text-blue-700">
                                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-blue-700"></div>
                                    <span className="text-xs">Loading violation details...</span>
                                </div>
                            </div>
                        )}

                        <Table className="min-w-full text-xs" style={{ tableLayout: 'fixed' }}>
                            <TableHeader>
                                <TableRow>
                                    <TableHead className="w-12 min-w-[3rem] text-xs px-2">Sl.No</TableHead>
                                    <TableHead className="w-20 min-w-[5rem] text-xs px-2">Image</TableHead>
                                    <TableHead className="w-24 min-w-[6rem] text-xs px-2">ID</TableHead>
                                    <TableHead className="w-20 min-w-[5rem] text-xs px-2">Status</TableHead>
                                    <TableHead className="w-28 min-w-[7rem] text-xs px-2">License plate</TableHead>
                                    <TableHead className="w-64 min-w-[16rem] text-xs px-2">Violation</TableHead>
                                    <TableHead className="w-20 min-w-[5rem] text-xs px-2">Location</TableHead>
                                    <TableHead className="w-32 min-w-[8rem] text-xs px-2">Time</TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                                                {isLoading ? (
                                    <TableRow>
                                        <TableCell colSpan="8" className="h-12 text-center text-xs py-1 px-2">Loading violations...</TableCell>
                                    </TableRow>
                                ) : (() => {
                                    return currentViolations.length > 0 ? (
                                        currentViolations.map((violation, index) => (
                                            <TableRow
                                                key={violation.id}
                                                onClick={() => !isLoadingViolationDetails && handleSelectViolation(violation)}
                                                className={`cursor-pointer hover:bg-gray-50 h-9 ${isLoadingViolationDetails ? 'opacity-50' : ''}`}
                                            >
                                                <TableCell className="text-xs text-gray-400 py-1 px-2">
                                    {((apiData.pagination.current_page - 1) * apiData.pagination.page_size) + index + 1}
                                </TableCell>
                                                <TableCell className="py-1 px-2">
                                                    <div className="w-16 h-12 bg-gray-200 rounded-lg flex items-center justify-center">
                                                        <img
                                                            src={violation.composite_image_path || 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgdmlld0JveD0iMCAwIDEwMCAxMDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIiBmaWxsPSIjRjNGNEY2Ii8+Cjx0ZXh0IHg9IjUwIiB5PSI1MCIgZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIiBmb250LXNpemU9IjEyIiBmaWxsPSIjNjc3NDhCIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+SW1hZ2U8L3RleHQ+Cjx0ZXh0IHg9IjUwIiB5PSI2NSIgZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIiBmb250LXNpemU9IjEyIiBmaWxsPSIjNjc3NDhCIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+Tm90IEF2YWlsYWJsZTwvdGV4dD4KPC9zdmc+'}
                                                            alt="Violation"
                                                            className="w-full h-full object-cover rounded-lg"
                                                                                            onError={(e) => {
                                    // Prevent infinite loop by checking if we're already on the fallback
                                                if (e.target.src !== getImagePath("Capture.PNG")) {
                e.target.src = getImagePath("Capture.PNG");
            } else {
                                        // If fallback also fails, hide the image to prevent infinite loop
                                        e.target.style.display = 'none';
                                    }
                                }}
                                                        />
                                                    </div>
                                                </TableCell>
                                                <TableCell className="font-mono text-xs py-1 px-2">{violation.id || '-'}</TableCell>
                                                <TableCell className="text-xs py-1 px-2">{violation.challan_status ? getStatusBadge(violation.challan_status) : '-'}</TableCell>
                                                <TableCell className="font-mono text-xs py-1 px-2">{violation.license_plate_number || '-'}</TableCell>
                                                <TableCell className="text-xs py-1 px-2">
                                                    {(() => {
                                                        if (!violation.violation_types) return '-';
                                                        
                                                        let violationTypes = [];
                                                        
                                                        // Ensure violation_types is a string before processing
                                                        if (typeof violation.violation_types !== 'string') {
                                                            violationTypes = [String(violation.violation_types || '')];
                                                        } else {
                                                        
                                                        // Parse the JSON string from API response
                                                        try {
                                                            const parsed = JSON.parse(violation.violation_types);
                                                            if (Array.isArray(parsed)) {
                                                                // Handle array format like ["Triple Riding"] or ["Signal Jumping", "Extra Passengers"]
                                                                violationTypes = parsed.map(type => typeof type === 'string' ? type.trim() : String(type).trim()).filter(type => type);
                                                            } else if (parsed && typeof parsed === 'string') {
                                                                // If it's a string, split by comma
                                                                violationTypes = parsed.split(',').map(type => type.trim()).filter(type => type);
                                                            } else {
                                                                violationTypes = [parsed];
                                                            }
                                                        } catch (error) {
                                                            // If JSON parsing fails, treat as comma-separated string
                                                            let rawTypes = violation.violation_types;
                                                            
                                                            // Ensure rawTypes is a string before processing
                                                            if (typeof rawTypes !== 'string') {
                                                                rawTypes = String(rawTypes || '');
                                                            }
                                                            
                                                            // Try different separators
                                                            if (rawTypes.includes(',')) {
                                                                violationTypes = rawTypes.split(',').map(type => type.trim()).filter(type => type);
                                                            } else if (rawTypes.includes(';')) {
                                                                violationTypes = rawTypes.split(';').map(type => type.trim()).filter(type => type);
                                                            } else if (rawTypes.includes('|')) {
                                                                violationTypes = rawTypes.split('|').map(type => type.trim()).filter(type => type);
                                                            } else {
                                                                // If no separators found, treat as single violation
                                                                violationTypes = [typeof rawTypes === 'string' ? rawTypes.trim() : String(rawTypes).trim()];
                                                            }
                                                        }
                                                        }
                                                        
                                                        // Clean up and filter out empty types
                                                        violationTypes = violationTypes
                                                            .filter(type => type && typeof type === 'string' && type.trim() !== '')
                                                            .map(type => typeof type === 'string' ? type.replace(/\\"/g, '"').trim() : String(type).trim())
                                                            .filter(type => type.length > 0);
                                                        
                                                        const totalViolations = violationTypes.length;
                                                        
                                                        if (totalViolations === 0) return '-';
                                                        
                                                        if (totalViolations <= 2) {
                                                            return (
                                                                <div className="flex flex-wrap gap-1">
                                                                    {violationTypes.map((type, index) => (
                                                                        <Badge key={index} className="bg-blue-100 text-blue-800 border-blue-200 text-xs hover:bg-blue-100 hover:text-blue-800 hover:border-blue-200">
                                                                            {type}
                                                                        </Badge>
                                                                    ))}
                                                                </div>
                                                            );
                                                        } else {
                                                            return (
                                                                <div className="flex flex-wrap gap-1">
                                                                    {violationTypes.slice(0, 2).map((type, index) => (
                                                                        <Badge key={index} className="bg-blue-100 text-blue-800 border-blue-200 text-xs hover:bg-blue-100 hover:text-blue-800 hover:border-blue-200">
                                                                            {type}
                                                                        </Badge>
                                                                    ))}
                                                                    <Badge className="bg-blue-100 text-blue-800 border-blue-200 text-xs hover:bg-blue-100 hover:text-blue-800 hover:border-blue-200">
                                                                        +{totalViolations - 2}
                                                                    </Badge>
                                                                </div>
                                                            );
                                                        }
                                                    })()}
                                                </TableCell>
                                                <TableCell className="w-20 min-w-[5rem] text-xs py-1 px-2">
                                                    <div className="text-xs leading-tight w-20 min-w-[5rem] max-w-20 overflow-hidden">
                                                        {violation.location_text ? (
                                                            (() => {
                                                                const parts = violation.location_text.split(',').map(part => part.trim()).filter(part => part.length > 0);
                                                                const firstLineParts = parts.slice(0, 2);
                                                                const secondLineParts = parts.slice(2);
                                                                
                                                                return (
                                                                    <>
                                                                        <div className="truncate w-full">{firstLineParts.join(', ')}{firstLineParts.length > 0 && parts.length > 2 ? ',' : ''}</div>
                                                                        {secondLineParts.length > 0 && (
                                                                            <div className="truncate w-full">{secondLineParts[0]}{secondLineParts.length > 1 ? '...' : ''}</div>
                                                                        )}
                                                                    </>
                                                                );
                                                            })()
                                                        ) : '-'}
                                                    </div>
                                                </TableCell>
                                                <TableCell className="text-xs py-1 px-2">
                                                    {violation.timestamp ? (
                                                        <>
                                                            {new Date(violation.timestamp + 'Z').toLocaleDateString('en-GB', {
                                                                day: 'numeric',
                                                                month: 'short',
                                                                year: 'numeric'
                                                            })} | {new Date(violation.timestamp + 'Z').toLocaleTimeString('en-US', {
                                                                hour: 'numeric',
                                                                minute: '2-digit',
                                                                hour12: true
                                                            })}
                                                        </>
                                                    ) : '-'}
                                                </TableCell>
                                            </TableRow>
                                        ))
                                    ) : (
                                        <TableRow>
                                            <TableCell colSpan="8" className="h-16 text-center text-sm py-1">
                                                {apiData.counts.total_count === 0 ? 'No Data Available' : 'No violations match the current filters.'}
                                            </TableCell>
                                        </TableRow>
                                    );
                                })()}
                            </TableBody>
                        </Table>
                    </div>

                    {/* Responsive Pagination Controls */}
                    {totalPages > 1 && (
                        <div className="flex flex-col items-center space-y-2 md:space-y-2 sm:space-y-1 py-4 md:py-4 sm:py-3">
                            {/* Page Info */}
                            <div className="text-xs text-gray-600">
                                Page {apiData.pagination.current_page} of {totalPages} 
                                ({apiData.pagination.total_items} total violations)
                            </div>
                            
                            {/* Pagination Buttons */}
                            <div className="flex items-center justify-center space-x-1 md:space-x-1 sm:space-x-0.5">
                            <button
                                onClick={handlePreviousPage}
                                disabled={!apiData.pagination.has_prev}
                                className={`w-6 h-6 md:w-6 md:h-6 sm:w-5 sm:h-5 rounded-sm border text-xs font-medium transition-colors ${!apiData.pagination.has_prev
                                    ? '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-6 h-6 rounded-sm border text-xs font-medium transition-colors ${apiData.pagination.current_page === 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-6 h-6 flex items-center justify-center text-xs text-gray-600 border border-gray-200 rounded-sm">
                                            ...
                                        </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-6 h-6 rounded-sm border text-xs font-medium transition-colors ${apiData.pagination.current_page === 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={!apiData.pagination.has_next}
                                className={`w-6 h-6 rounded-sm border text-xs font-medium transition-colors ${!apiData.pagination.has_next
                                    ? '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>
                </div>

                {/* Footer */}
                <div className="bg-white px-4 py-2 text-left text-sm text-gray-400">
                    <p>© 2025 PushpakAI. All rights reserved.</p>
                </div>
            </div>

          
        </div>
    );
}