import React, { useState, useEffect, useMemo } from 'react';
import { format } from 'date-fns';
import { useNavigate, useParams } from 'react-router-dom';
import api from '../lib/api';
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";
import { Input } from "@/components/ui/input";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription, DialogTrigger } from "@/components/ui/dialog";

import { FileDown, Pencil, X, Users, CheckCircle } from 'lucide-react';
import Zoom from 'react-medium-image-zoom';
import 'react-medium-image-zoom/dist/styles.css';
import { generatePdfReport } from '../lib/reportGenerator';
import { getImagePath } from '../lib/utils';



// Helper for status badge (unchanged)
const getStatusBadge = (status, reason = '') => {
    switch (status?.toLowerCase()) {
        case 'raised':
            return <Badge variant="success" className="text-base">Raised</Badge>;
        case 'rejected':
            return (
                <div className="flex flex-col items-start">
                    <Badge variant="destructive" className="text-base">Rejected</Badge>
                    <p className="text-sm text-gray-500 mt-1">Reason: {reason}</p>
                </div>
            );
        default:
            return <Badge variant="secondary" className="text-base">New</Badge>;
    }
};



// Dummy Vahan Data (unchanged)
const dummyVahanData = {
    owner: { title: "Owner Details", details: [{ label: "Name", value: "-" }, { label: "Address", value: "-" }] },
    vehicle: { title: "Vehicle Details", details: [{ label: "Chassis Number", value: "-" }, { label: "Engine Number", value: "-" }, { label: "Fuel Type", value: "-" }, { label: "Registration Status", value: "-" }] },
    compliance: { title: "Compliance Details", details: [{ label: "Insurance Policy", value: "-" }, { label: "Insurance Validity", value: "-" }, { label: "Fitness Certificate", value: "-" }, { label: "Financing", value: "-" }, { label: "Pending Challans", value: "-" }] }
};

export function ViolationDetail({ initialViolation, onBack, onUpdate, onNextViolation }) {
    const navigate = useNavigate();
    const { id } = useParams(); // Get violation ID from URL
    const [violation, setViolation] = useState(initialViolation);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isGeneratingReport, setIsGeneratingReport] = useState(false);
    const [showUserMenu, setShowUserMenu] = useState(false);

    // Initialize loading state based on whether we have data or need to fetch
    const [isLoading, setIsLoading] = useState(!initialViolation && !id);

    // State for mobile menu
    const [showMobileMenu, setShowMobileMenu] = useState(false);
    
    // State for sidebar toggle
    const [showSidebar, setShowSidebar] = useState(true);



    // --- State for In-Place License Plate Editing ---
    const [isEditingPlate, setIsEditingPlate] = useState(false);
    const [newPlateNumber, setNewPlateNumber] = useState('');
    const [magnifierPosition, setMagnifierPosition] = useState({ x: 0, y: 0, imageX: 0, imageY: 0 });
    const [licensePlateImageError, setLicensePlateImageError] = useState(false);
    const [showMagnifier, setShowMagnifier] = useState(false);

    // --- State for Violation Types Management ---
    const [allViolationTypes, setAllViolationTypes] = useState([]);
    const [selectedViolationType, setSelectedViolationType] = useState('');
    const [showViolationTypesDropdown, setShowViolationTypesDropdown] = useState(false);
    const [violationTypeSearch, setViolationTypeSearch] = useState('');
    const [isLoadingViolationTypes, setIsLoadingViolationTypes] = useState(false);
    const [isUpdatingViolationTypes, setIsUpdatingViolationTypes] = useState(false);
    
    // Toast notification state
    const [toast, setToast] = useState({ show: false, message: '', type: 'success' });

    // Reset license plate image error state when violation changes
    useEffect(() => {
        setLicensePlateImageError(false);
    }, [violation?.id]);

    // Fetch violation details from API when component mounts
    useEffect(() => {
        const fetchViolationDetails = async () => {
            // Use URL parameter if available, otherwise fall back to initialViolation
            const violationId = id || initialViolation?.id;

            if (!violationId) {
                console.error('No violation ID available');
                // Show error state instead of loading indefinitely
                setIsLoading(false);
                setViolation(null);
                return;
            }

            setIsLoading(true);
            try {
                // Use the configured API endpoint
                const response = await api.get(`/violations/${violationId}`);

                // Handle nested response structure
                const violationData = response.data.violation || response.data;

                // Helper function to ensure we have full URLs
                const ensureFullImageUrl = (imagePath) => {
                    if (!imagePath || imagePath === 'null' || imagePath === 'undefined') return null;
                    if (imagePath.startsWith('http')) return imagePath;

                    // Use /images/ path directly
                    if (imagePath.startsWith('/images/')) {
                        return `https://cyberhawk.pushpak.cloud${imagePath}`;
                    }

                    // If path doesn't start with /images/, assume it should be in /images/
                    if (imagePath.startsWith('/')) {
                        // Convert any other path to /images/ path
                        const imageName = imagePath.split('/').pop(); // Get the filename
                        return `https://cyberhawk.pushpak.cloud/images/${imageName}`;
                    }

                    // If no leading slash, assume it's just a filename
                    return `https://cyberhawk.pushpak.cloud/images/${imagePath}`;
                };

                // If we have initialViolation data, merge it with the API response
                // Otherwise, use only the API response
                let mergedData;
                if (initialViolation) {
                    // Convert any path to /images/ path
                    const convertImagePath = (path) => {
                        if (!path) return null;
                        if (path.startsWith('/images/')) return path;
                        
                        // If it's any other path, extract filename and use /images/
                        const imageName = path.split('/').pop(); // Get the filename
                        return `/images/${imageName}`;
                    };

                    mergedData = {
                        ...violationData,
                        officer: response.data.officer || violationData.officer,
                        vehicle: response.data.vehicle || violationData.vehicle,
                        // Convert to /images/ and ensure we always have full URLs for images
                        composite_image_path: ensureFullImageUrl(convertImagePath(initialViolation?.composite_image_path)) || ensureFullImageUrl(convertImagePath(violationData?.composite_image_path)),
                        license_plate_crop_path: ensureFullImageUrl(convertImagePath(initialViolation?.license_plate_crop_path)) || ensureFullImageUrl(convertImagePath(violationData?.license_plate_crop_path)),
                        // Preserve all other important fields from the violations list API
                        junction_name: initialViolation?.junction_name || violationData?.junction_name,
                        police_station: initialViolation?.police_station || violationData?.police_station,
                        police_station_code: initialViolation?.police_station_code || violationData?.police_station_code,
                        junction_code: initialViolation?.junction_code || violationData?.junction_code,
                        location_text: initialViolation?.location_text || violationData?.location_text,
                        latitude: initialViolation?.latitude || violationData?.latitude,
                        longitude: initialViolation?.longitude || violationData?.longitude,
                        roi: initialViolation?.roi || violationData?.roi,
                        timestamp: initialViolation?.timestamp || violationData?.timestamp,
                        license_plate_number: initialViolation?.license_plate_number || violationData?.license_plate_number,
                        challan_status: initialViolation?.challan_status || violationData?.challan_status,
                        rejection_reason: initialViolation?.rejection_reason || violationData?.rejection_reason,
                        device_id: initialViolation?.device_id || violationData?.device_id,
                        login_id: initialViolation?.login_id || violationData?.login_id
                    };


                } else {
                    // Standalone mode - use only API response
                    // Convert any path to /images/ path
                    const convertImagePath = (path) => {
                        if (!path) return null;
                        if (path.startsWith('/images/')) return path;
                        
                        // If it's any other path, extract filename and use /images/
                        const imageName = path.split('/').pop(); // Get the filename
                        return `/images/${imageName}`;
                    };

                    mergedData = {
                        ...violationData,
                        officer: response.data.officer || violationData.officer,
                        vehicle: response.data.vehicle || violationData.vehicle,
                        // Convert to /images/ and ensure we always have full URLs for images
                        composite_image_path: ensureFullImageUrl(convertImagePath(violationData?.composite_image_path)),
                        license_plate_crop_path: ensureFullImageUrl(convertImagePath(violationData?.license_plate_crop_path))
                    };


                }

                setViolation(mergedData);
                setNewPlateNumber(mergedData.license_plate_number || '');

                // Fetch violation types after setting violation data
                fetchAllViolationTypes();

            } catch (error) {
                console.error('Error fetching violation details:', error);
                // Use initial data as fallback if available
                if (initialViolation) {
                    setViolation(initialViolation);
                    setNewPlateNumber(initialViolation.license_plate_number || '');
                } else {
                    // If no initial data and API fails, show error state
                    setViolation(null);
                }
            } finally {
                setIsLoading(false);
            }
        };

        const fetchAllViolationTypes = async () => {
            setIsLoadingViolationTypes(true);
            try {
                const response = await api.get('/violation-types/');
                const data = response.data;
                // Ensure we have valid data
                if (data && (Array.isArray(data) || typeof data === 'object')) {
                    setAllViolationTypes(data);
                } else {
                    console.warn('Invalid violation types data received in ViolationDetail:', data);
                    setAllViolationTypes([]);
                }
            } catch (error) {
                console.error('Failed to fetch violation types:', error);
                // No fallback to mock data - let it be empty if API fails
                setAllViolationTypes([]);
            } finally {
                setIsLoadingViolationTypes(false);
            }
        };

        // Always fetch if we have a valid ID, regardless of initialViolation
        if (id || initialViolation?.id) {
            fetchViolationDetails();
            fetchAllViolationTypes();
        } else {
            // If no ID is available, show error state immediately
            setIsLoading(false);
            setViolation(null);
        }
    }, [id, initialViolation?.id, navigate]);

    // Additional useEffect to handle ID changes (useful for refresh scenarios)
    useEffect(() => {
        if (id && !violation && !isLoading) {
            // If we have an ID but no violation data and not loading, try to fetch again
            const fetchViolationDetails = async () => {
                setIsLoading(true);
                try {
                    const response = await api.get(`/violations/${id}`);
                    const violationData = response.data.violation || response.data;
                    
                    // Helper function to ensure we have full URLs
                    const ensureFullImageUrl = (imagePath) => {
                        if (!imagePath || imagePath === 'null' || imagePath === 'undefined') return null;
                        if (imagePath.startsWith('http')) return imagePath;
                        if (imagePath.startsWith('/images/')) {
                            return `https://cyberhawk.pushpak.cloud${imagePath}`;
                        }
                        if (imagePath.startsWith('/')) {
                            // Convert any other path to /images/ path
                            const imageName = imagePath.split('/').pop(); // Get the filename
                            return `https://cyberhawk.pushpak.cloud/images/${imageName}`;
                        }
                        // If no leading slash, assume it's just a filename
                        return `https://cyberhawk.pushpak.cloud/images/${imagePath}`;
                    };
                    
                    const mergedData = {
                        ...violationData,
                        officer: response.data.officer || violationData.officer,
                        vehicle: response.data.vehicle || violationData.vehicle,
                        composite_image_path: ensureFullImageUrl(violationData?.composite_image_path),
                        license_plate_crop_path: ensureFullImageUrl(violationData?.license_plate_crop_path)
                    };
                    
                    setViolation(mergedData);
                    setNewPlateNumber(mergedData.license_plate_number || '');
                } catch (error) {
                    console.error('Error fetching violation details on ID change:', error);
                    setViolation(null);
                } finally {
                    setIsLoading(false);
                }
            };
            
            fetchViolationDetails();
        }
    }, [id, violation, isLoading]);



    // Use provided functions from parent component, or navigate back if in standalone mode
    const handleBackToList = onBack || (() => navigate('/dashboard'));
    const handleUpdateViolation = onUpdate || (() => { }); // No-op if no parent handler

    // Retry function to refetch violation data
    const handleRetry = async () => {
        const violationId = id || initialViolation?.id;
        if (!violationId) {
            navigate('/dashboard');
            return;
        }

        setIsLoading(true);
        try {
            const response = await api.get(`/violations/${violationId}`);
            const violationData = response.data.violation || response.data;
            
            // Helper function to ensure we have full URLs
            const ensureFullImageUrl = (imagePath) => {
                if (!imagePath || imagePath === 'null' || imagePath === 'undefined') return null;
                if (imagePath.startsWith('http')) return imagePath;
                if (imagePath.startsWith('/images/')) {
                    return `https://cyberhawk.pushpak.cloud${imagePath}`;
                }
                if (imagePath.startsWith('/')) {
                    // Convert any other path to /images/ path
                    const imageName = imagePath.split('/').pop(); // Get the filename
                    return `https://cyberhawk.pushpak.cloud/images/${imageName}`;
                }
                // If no leading slash, assume it's just a filename
                return `https://cyberhawk.pushpak.cloud/images/${imagePath}`;
            };

            const mergedData = {
                ...violationData,
                officer: response.data.officer || violationData.officer,
                vehicle: response.data.vehicle || violationData.vehicle,
                composite_image_path: ensureFullImageUrl(violationData?.composite_image_path),
                license_plate_crop_path: ensureFullImageUrl(violationData?.license_plate_crop_path)
            };

            setViolation(mergedData);
            setNewPlateNumber(mergedData.license_plate_number || '');
        } catch (error) {
            console.error('Error retrying violation fetch:', error);
            setViolation(null);
        } finally {
            setIsLoading(false);
        }
    };

    // Handle next violation - either use parent function or implement standalone logic
    const handleNextViolation = onNextViolation || (async () => {
        try {
            // In standalone mode, fetch violations to find the next new one
            const response = await api.get('/violations/');
            const violationsData = response.data?.violations || [];

            if (violationsData.length === 0) {
                navigate('/dashboard');
                return;
            }

            // Find current violation index
            const currentIndex = violationsData.findIndex(v => v.id === violation?.id);
            if (currentIndex === -1) {
                navigate('/dashboard');
                return;
            }

            // Find next NEW violation starting from current position
            let nextNewViolation = null;
            for (let i = currentIndex + 1; i < violationsData.length; i++) {
                if (violationsData[i].challan_status?.toLowerCase() === 'new') {
                    nextNewViolation = violationsData[i];
                    break;
                }
            }

            // If no next NEW violation found, search from beginning
            if (!nextNewViolation) {
                for (let i = 0; i < currentIndex; i++) {
                    if (violationsData[i].challan_status?.toLowerCase() === 'new') {
                        nextNewViolation = violationsData[i];
                        break;
                    }
                }
            }

            if (nextNewViolation) {
                // Navigate to the next new violation
                navigate(`/violation/${nextNewViolation.id}`);
            } else {
                // No more new violations, go back to dashboard
                navigate('/dashboard');
            }
        } catch (error) {
            console.error('Failed to find next violation:', error);
            navigate('/dashboard');
        }
    });


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

    // Filter violation types based on search (handles category-based structure)
    const filteredViolationTypes = useMemo(() => {
        // Get current violation types for this violation
        let currentTypes = [];
        try {
            currentTypes = violation?.violation_types ? JSON.parse(violation.violation_types) : [];
        } catch (error) {
            currentTypes = Array.isArray(violation?.violation_types) ? violation.violation_types : [violation?.violation_types].filter(Boolean);
        }
        currentTypes = Array.isArray(currentTypes) ? currentTypes : [currentTypes].filter(Boolean);

        if (!Array.isArray(allViolationTypes) && typeof allViolationTypes === 'object') {
            // Handle category-based structure from API
            const allTypes = [];
            Object.entries(allViolationTypes).forEach(([category, violations]) => {
                if (Array.isArray(violations)) {
                    violations.forEach(violationType => {
                        if (violationType.toLowerCase().includes(violationTypeSearch.toLowerCase())) {
                            allTypes.push(violationType);
                        }
                    });
                } else if (typeof violations === 'string' && violations.toLowerCase().includes(violationTypeSearch.toLowerCase())) {
                    allTypes.push(violations);
                }
            });

            // Sort: current types first, then others
            const sortedTypes = allTypes.sort((a, b) => {
                const aIsCurrent = currentTypes.includes(a);
                const bIsCurrent = currentTypes.includes(b);
                if (aIsCurrent && !bIsCurrent) return -1;
                if (!aIsCurrent && bIsCurrent) return 1;
                return a.localeCompare(b);
            });

            return sortedTypes;
        } else {
            // Handle flat array structure (fallback)
            const types = allViolationTypes.filter(type =>
                type.toLowerCase().includes(violationTypeSearch.toLowerCase())
            );

            // Sort: current types first, then others
            const sortedTypes = types.sort((a, b) => {
                const aIsCurrent = currentTypes.includes(a);
                const bIsCurrent = currentTypes.includes(b);
                if (aIsCurrent && !bIsCurrent) return -1;
                if (!aIsCurrent && bIsCurrent) return 1;
                return a.localeCompare(b);
            });

            return sortedTypes;
        }
    }, [violation?.violation_types, allViolationTypes, violationTypeSearch]);

    // Toast notification function
    const showToast = (message, type = 'success') => {
        setToast({ show: true, message, type });
        setTimeout(() => {
            setToast({ show: false, message: '', type: 'success' });
        }, 3000);
    };

    // Unchanged handler functions
    const handleRaiseChallan = async () => {
        setIsSubmitting(true);
        try {
            console.log('Raising challan for violation:', violation.id);

            // Call the actual API to raise challan
            const response = await api.patch(`/violations/${violation.id}/raise`, {});

            console.log('Raise challan API Response:', response.data);

            // Check if the API call was successful (ResponseCode "0" indicates success)
            if (response.data && response.data.ResponseCode === "0") {
                // Update the violation status to 'raised' since the API was successful
                const updatedViolation = {
                    ...violation,
                    challan_status: 'raised'
                };

                console.log('Updated violation after raising challan:', updatedViolation);

                setViolation(updatedViolation);
                if (handleUpdateViolation) {
                    handleUpdateViolation(updatedViolation);
                }

                // Show success message with the challan number from ResponseDesc
                const challanNumber = response.data.ResponseDesc || 'Unknown';
                
                // Show success toast message
                showToast(`Challan raised successfully! Challan Number: ${challanNumber}`);

                // Navigate to next violation after showing toaster for 1.5 seconds
                setTimeout(() => {
                    if (handleNextViolation) {
                        handleNextViolation();
                    } else {
                        navigate('/dashboard');
                    }
                }, 1500);
            } else {
                // Handle API error response
                const errorMessage = response.data?.ResponseDesc || 'Failed to raise challan';
                console.error('API Error:', response.data);
                showToast(errorMessage, 'error');
            }
        } catch (error) {
            console.error("Failed to raise challan", error);
            showToast('Failed to raise challan', 'error');
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleRejectChallan = async () => {
        setIsSubmitting(true);
        try {
            // Store the current image paths and other important data before rejection
            const currentImagePath = violation?.composite_image_path;
            const currentLicensePlatePath = violation?.license_plate_crop_path;
            const currentLicensePlateNumber = violation?.license_plate_number;
            const currentViolationTypes = violation?.violation_types;
            const currentLocationText = violation?.location_text;
            const currentTimestamp = violation?.timestamp;
            const currentVehicleData = violation?.vehicle;
            const currentDeviceId = violation?.device_id;
            const currentOfficerData = violation?.officer;
            const currentJunction = violation?.junction;

            // Use PATCH method as per API documentation with default rejection reason
            const response = await api.patch(`/violations/${violation.id}/reject`, { reason: "Violation rejected by officer" });

            console.log('Reject API Response:', response.data);
            console.log('Current device_id before rejection:', currentDeviceId);

            // Handle nested response structure for reject API
            const rejectResponseData = response.data.violation || response.data;
            console.log('Device ID in API response:', rejectResponseData.device_id);

            // Preserve ALL the original data that might be missing from the response
            const updatedViolation = {
                ...rejectResponseData,
                composite_image_path: currentImagePath || rejectResponseData.composite_image_path,
                license_plate_crop_path: currentLicensePlatePath || rejectResponseData.license_plate_path,
                license_plate_number: currentLicensePlateNumber || rejectResponseData.license_plate_number,
                violation_types: currentViolationTypes || rejectResponseData.violation_types,
                location_text: currentLocationText || rejectResponseData.location_text,
                timestamp: currentTimestamp || rejectResponseData.timestamp,
                vehicle: currentVehicleData || rejectResponseData.vehicle,
                device_id: currentDeviceId || rejectResponseData.device_id,
                officer: currentOfficerData || rejectResponseData.officer,
                junction: currentJunction || rejectResponseData.junction
            };

            console.log('Updated violation after preserving data:', updatedViolation);

            setViolation(updatedViolation);
            if (handleUpdateViolation) {
                handleUpdateViolation(updatedViolation);
            }
            
            // Show success toast message
            showToast('Challan rejected successfully!');

            // Navigate to next violation after showing toaster for 1.5 seconds
            setTimeout(() => {
                if (handleNextViolation) {
                    handleNextViolation();
                } else {
                    navigate('/dashboard');
                }
            }, 1500);
        } catch (error) {
            console.error("Failed to reject violation", error);
            showToast('Failed to reject challan', 'error');
        } finally {
            setIsSubmitting(false);
        }
    };

    const handleGenerateReport = async () => {
        setIsGeneratingReport(true);
        try {
            await generatePdfReport(violation, dummyVahanData);
        } catch (error) {
            console.error("Failed to generate report:", error);
        } finally {
            setIsGeneratingReport(false);
        }
    };

    // --- New handler to save the updated license plate ---
    const handleUpdatePlate = async () => {
        if (!newPlateNumber || newPlateNumber.trim() === '') {
            return;
        }

        setIsSubmitting(true);
        try {
            console.log('Current violation data before update:', violation);

            // Step 1: Update the license plate number via API
            const updateResponse = await api.patch(`/violations/${violation.id}/update-plate`, {
                new_plate_number: newPlateNumber.toUpperCase().trim(),
            });

            console.log('Update plate API response:', updateResponse.data);

            // Step 2: Immediately refresh the violation data to get updated vehicle details
            try {
                // Call the violations API to get the latest data with updated vehicle details
                const refreshResponse = await api.get(`/violations/${violation.id}`);

                // Handle the API response structure properly
                // The API returns: { violation: {...}, officer: {...}, vehicle: {...} }
                const responseData = refreshResponse.data;

                // Create the updated violation object with fresh data
                const refreshedViolation = {
                    ...violation, // Keep existing data as fallback
                    ...responseData.violation, // Override with fresh violation data
                    officer: responseData.officer || violation.officer, // Update officer data
                    vehicle: responseData.vehicle || violation.vehicle, // Update vehicle data
                    license_plate_number: newPlateNumber.toUpperCase().trim() // Ensure new plate number is set
                };

                // Update both local state and parent component
                setViolation(refreshedViolation);
                if (handleUpdateViolation) {
                    handleUpdateViolation(refreshedViolation);
                }

            } catch (refreshError) {
                console.error('Failed to refresh violation data after plate update:', refreshError);

                // Fallback: Use the update response data if available
                const updateResponseData = updateResponse.data.violation || updateResponse.data;
                const fallbackViolation = {
                    ...violation,
                    ...updateResponseData,
                    license_plate_number: newPlateNumber.toUpperCase().trim()
                };

                setViolation(fallbackViolation);
                if (handleUpdateViolation) {
                    handleUpdateViolation(fallbackViolation);
                }
            }

            setIsEditingPlate(false); // Exit editing mode

        } catch (error) {
            console.error("Failed to update license plate", error);
            // Keep the form in editing mode if there's an error
        } finally {
            setIsSubmitting(false);
        }
    };

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

    // --- Violation Type Management Functions ---
    const handleAddViolationType = async (newType) => {
        if (!newType || newType.trim() === '') {
            return;
        }

        try {
            // Get current violation types
            let currentTypes = [];
            try {
                currentTypes = violation?.violation_types ? JSON.parse(violation.violation_types) : [];
            } catch (error) {
                currentTypes = Array.isArray(violation?.violation_types) ? violation.violation_types : [violation?.violation_types].filter(Boolean);
            }

            // Check if type already exists
            if (currentTypes.includes(newType)) {
                return;
            }

            // Add new type
            const updatedTypes = [...currentTypes, newType];

            // Try to update via API first
            try {
                setIsUpdatingViolationTypes(true);
                console.log('Current violation data before violation types update:', violation);

                const response = await api.patch(`/violations/${violation.id}/update-violation-type`, {
                    new_violation_types: updatedTypes
                });

                console.log('Update violation types API response:', response.data);

                // Update local state with API response
                // Handle nested response structure for update-violation-type API
                const updateTypesResponseData = response.data.violation || response.data;

                // Use the helper function to safely merge data
                const updatedViolation = mergeViolationData(
                    violation,
                    response.data,
                    { violation_types: JSON.stringify(updatedTypes) }
                );

                console.log('Updated violation data:', updatedViolation);

                setViolation(updatedViolation);
                if (handleUpdateViolation) {
                    handleUpdateViolation(updatedViolation);
                }
            } catch (apiError) {
                console.warn("API update failed, updating local state only:", apiError);

                // Fallback: update local state only
                const updatedViolation = {
                    ...violation,
                    violation_types: JSON.stringify(updatedTypes)
                };
                setViolation(updatedViolation);
                if (handleUpdateViolation) {
                    handleUpdateViolation(updatedViolation);
                }
            } finally {
                setIsUpdatingViolationTypes(false);
            }

            setSelectedViolationType('');
        } catch (error) {
            console.error("Failed to add violation type:", error);
        }
    };

    const handleRemoveViolationType = async (typeToRemove) => {
        try {
            // Get current violation types
            let currentTypes = [];
            try {
                currentTypes = violation?.violation_types ? JSON.parse(violation.violation_types) : [];
            } catch (error) {
                currentTypes = Array.isArray(violation?.violation_types) ? violation.violation_types : [violation?.violation_types].filter(Boolean);
            }

            // Remove the type
            const updatedTypes = currentTypes.filter(type => type !== typeToRemove);

            // Try to update via API first
            try {
                setIsUpdatingViolationTypes(true);
                console.log('Current violation data before violation types update:', violation);

                const response = await api.patch(`/violations/${violation.id}/update-violation-type`, {
                    new_violation_types: updatedTypes
                });

                console.log('Update violation types API response:', response.data);

                // Update local state with API response
                // Handle nested response structure for update-violation-type API
                const updateTypesResponseData = response.data.violation || response.data;

                // Use the helper function to safely merge data
                const updatedViolation = mergeViolationData(
                    violation,
                    response.data,
                    { violation_types: JSON.stringify(updatedTypes) }
                );

                console.log('Updated violation data:', updatedViolation);

                setViolation(updatedViolation);
                if (handleUpdateViolation) {
                    handleUpdateViolation(updatedViolation);
                }
            } catch (apiError) {
                console.warn("API update failed, updating local state only:", apiError);

                // Fallback: update local state only
                const updatedViolation = {
                    ...violation,
                    violation_types: JSON.stringify(updatedTypes)
                };
                setViolation(updatedViolation);
                if (handleUpdateViolation) {
                    handleUpdateViolation(updatedViolation);
                }
            } finally {
                setIsUpdatingViolationTypes(false);
            }
        } catch (error) {
            console.error("Failed to remove violation type:", error);
        }
    };

    // Helper function to safely merge API response with existing violation data
    const mergeViolationData = (existingData, apiResponse, updates = {}) => {
        // Start with existing data
        const mergedData = { ...existingData };

        // Apply any specific updates (like license plate number or violation types)
        Object.assign(mergedData, updates);

        // If API response has data, merge it intelligently
        if (apiResponse) {
            const responseData = apiResponse.violation || apiResponse;

            // Only merge non-null/undefined values from API response
            Object.entries(responseData).forEach(([key, value]) => {
                if (value !== null && value !== undefined && value !== '') {
                    mergedData[key] = value;
                }
            });
        }

        // Ensure critical fields are preserved
        const criticalFields = [
            'id', 'device_id', 'login_id', 'police_station', 'police_station_code',
            'junction_name', 'junction_code', 'location_text', 'latitude', 'longitude',
            'roi', 'timestamp', 'license_plate_crop_path', 'composite_image_path',
            'challan_status', 'rejection_reason', 'officer', 'vehicle', 'junction'
        ];

        criticalFields.forEach(field => {
            if (existingData[field] && !mergedData[field]) {
                mergedData[field] = existingData[field];
            }
        });

        console.log('Merged violation data:', mergedData);
        return mergedData;
    };



    // Handle different image path formats
    // Enhanced to handle various API response formats
    const getImageUrl = (violation) => {
        // Try different possible field names for the composite image
        const imagePath = violation?.composite_image_path ||
            violation?.composite_image ||
            violation?.image_path ||
            violation?.image;

        // If no image path found, try to find any image field in the violation data
        if (!imagePath) {
            const allFields = Object.keys(violation || {});
            const imageFields = allFields.filter(field =>
                field.toLowerCase().includes('image') ||
                field.toLowerCase().includes('photo') ||
                field.toLowerCase().includes('img')
            );

            if (imageFields.length > 0) {
                const firstImageField = imageFields[0];
                const alternativeImagePath = violation[firstImageField];
                if (alternativeImagePath) {
                    return alternativeImagePath;
                }
            }
        }

        if (!imagePath || imagePath === 'null' || imagePath === 'undefined') {
            console.log('No image path, using fallback');
            // Return a data URI for a simple placeholder instead of a file that might not exist
            return 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgdmlld0JveD0iMCAwIDEwMCAxMDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIiBmaWxsPSIjRjNGNEY2Ii8+Cjx0ZXh0IHg9IjUwIiB5PSI1MCIgZm9ntC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIiBmb250LXNpemU9IjEyIiBmaWxsPSIjNjc3NDhCIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+SW1hZ2U8L3RleHQ+Cjx0ZXh0IHg9IjUwIiB5PSI2NSIgZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIiBmb250LXNpemU9IjEyIiBmaWxsPSIjNjc3NDhCIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+Tm90IEF2YWlsYWJsZTwvdGV4dD4KPC9zdmc+';
        }

        // If it's already a full URL, use it directly
        if (imagePath.startsWith('http')) {
            console.log('Using full URL directly:', imagePath);
            return imagePath;
        }

        // Convert any path to /images/ paths for violation detail images
        if (imagePath.startsWith('/images/')) {
            const fullUrl = `https://cyberhawk.pushpak.cloud${imagePath}`;
            console.log('Constructed full URL from /images/ path:', fullUrl);
            return fullUrl;
        }

        // If path doesn't start with /images/, convert it to /images/
        if (imagePath.startsWith('/')) {
            const imageName = imagePath.split('/').pop(); // Get the filename
            const newPath = `/images/${imageName}`;
            console.log(`Converting path to /images/: ${imagePath} → ${newPath}`);
            const fullUrl = `https://cyberhawk.pushpak.cloud${newPath}`;
            console.log('Constructed full URL from converted path:', fullUrl);
            return fullUrl;
        }

        // If the path doesn't start with /, try to construct a full URL
        if (imagePath && !imagePath.startsWith('/')) {
            const fullUrl = `https://cyberhawk.pushpak.cloud/images/${imagePath}`;
            console.log('Constructed full URL from filename:', fullUrl);
            return fullUrl;
        }

        // Default fallback - but check if the file actually exists to prevent 404 loops
        console.log('Using default fallback image');
        // Return a data URI for a simple placeholder instead of a file that might not exist
        return 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgdmlld0JveD0iMCAwIDEwMCAxMDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIiBmaWxsPSIjRjNGNEY2Ii8+Cjx0ZXh0IHg9IjUwIiB5PSI1MCIgZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIiBmb250LXNpemU9IjEyIiBmaWxsPSIjNjc3NDhCIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+SW1hZ2U8L3RleHQ+Cjx0ZXh0IHg9IjUwIiB5PSI2NSIgZm9udC1mYW1pbHk9IkFyaWFsLCBzYW5zLXNlcmlmIiBmb250LXNpemU9IjEyIiBmaWxsPSIjNjc3NDhCIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIiBkeT0iLjNlbSI+Tm90IEF2YWlsYWJsZTwvdGV4dD4KPC9zdmc+';
    };

    console.log('About to construct image URLs for violation:', violation);
    const imageUrl = getImageUrl(violation);
    console.log('Final composite image URL:', imageUrl);

    // Helper function to get license plate image URL
    // Enhanced to handle various API response formats
    const getLicensePlateImageUrl = (violation) => {
        // Try different possible field names for the license plate image
        const licensePlatePath = violation?.license_plate_crop_path ||
            violation?.license_plate_image ||
            violation?.plate_image ||
            violation?.plate_crop_path;

        // If no license plate path found, try to find any plate-related field
        if (!licensePlatePath) {
            const allFields = Object.keys(violation || {});
            const plateFields = allFields.filter(field =>
                field.toLowerCase().includes('plate') ||
                field.toLowerCase().includes('license') ||
                field.toLowerCase().includes('crop')
            );

            if (plateFields.length > 0) {
                const firstPlateField = plateFields[0];
                const alternativePlatePath = violation[firstPlateField];
                if (alternativePlatePath) {
                    return alternativePlatePath;
                }
            }
        }

        if (!licensePlatePath || licensePlatePath === 'null' || licensePlatePath === 'undefined') {
            return null;
        }

        // If it's already a full URL, use it directly (this should be the case now)
        if (licensePlatePath.startsWith('http')) {
            return licensePlatePath;
        }

        // Convert any path to /images/ paths (since we only use /images/ now)
        if (licensePlatePath.startsWith('/images/')) {
            const fullUrl = `https://cyberhawk.pushpak.cloud${licensePlatePath}`;
            return fullUrl;
        }

        // If path doesn't start with /images/, convert it to /images/
        if (licensePlatePath.startsWith('/')) {
            const imageName = licensePlatePath.split('/').pop(); // Get the filename
            const newPath = `/images/${imageName}`;
            const fullUrl = `https://cyberhawk.pushpak.cloud${newPath}`;
            return fullUrl;
        }

        // If the path doesn't start with /, try to construct a full URL
        if (licensePlatePath && !licensePlatePath.startsWith('/')) {
            const fullUrl = `https://cyberhawk.pushpak.cloud/images/${licensePlatePath}`;
            return fullUrl;
        }

        // Return as is for other cases
        return licensePlatePath;
    };

    const licensePlateImageUrl = getLicensePlateImageUrl(violation);

    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 lg:p-4 md:p-4 sm:p-2 xs:p-2 space-y-2">
                    {/* Violations - Selected */}
                    <div 
                        className="flex items-center justify-between p-3 lg:p-3 md:p-3 sm:p-2 xs:p-2 rounded-lg bg-blue-50 cursor-pointer hover:bg-blue-100 transition-colors"
                        onClick={() => navigate('/dashboard')}
                    >
                        <div className="flex items-center space-x-3 lg:space-x-3 md:space-x-3 sm:space-x-2 xs:space-x-1">
                            <div className="w-5 h-5 lg:w-5 lg:h-5 md:w-5 md:h-5 sm:w-4 sm:h-4 xs:w-3 xs:h-3 flex items-center justify-center">
                                <svg className="w-5 h-5 lg:w-5 lg:h-5 md:w-5 md:h-5 sm:w-4 sm:h-4 xs:w-3 xs:h-3 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 lg:text-sm md:text-sm sm:text-xs xs:text-xs font-medium text-blue-700">Violations</span>
                            )}
                        </div>
                        {showSidebar && (
                            <div className="w-2 h-2 lg:w-2 lg:h-2 md:w-2 md:h-2 sm:w-1.5 sm:h-1.5 xs:w-1 xs:h-1 bg-blue-500 rounded-full"></div>
                        )}
                    </div>
                    
                    {/* Constables - Unselected */}
                    <div 
                        className="flex items-center justify-between p-3 lg:p-3 md:p-3 sm:p-2 xs:p-2 rounded-lg bg-gray-50 cursor-pointer hover:bg-gray-100 transition-colors"
                        onClick={() => navigate('/constables')}
                    >
                        <div className="flex items-center space-x-3 lg:space-x-3 md:space-x-3 sm:space-x-2 xs:space-x-1">
                            <div className="w-5 h-5 lg:w-5 lg:h-5 md:w-5 md:h-5 sm:w-4 sm:h-4 xs:w-3 xs:h-3 flex items-center justify-center">
                                <svg className="w-5 h-5 lg:w-5 lg:h-5 md:w-5 md:h-5 sm:w-4 sm:h-4 xs:w-3 xs:h-3 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 lg:text-sm md:text-sm sm:text-xs xs:text-xs font-medium text-gray-600">Constables</span>
                            )}
                        </div>
                    </div>
                </nav>
            </div>

            {/* 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"
                                onClick={() => {
                                    navigate('/dashboard');
                                    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-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>
            )}

            {/* Main Content Area */}
            <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'}`}>
                {/* Toast Notification */}
                {toast.show && (
                    <div className={`fixed top-20 md:top-20 sm:top-16 right-6 md:right-4 sm:right-3 z-50 px-4 md:px-3 sm:px-2 py-3 md:py-2 sm:py-1.5 rounded-lg shadow-lg transition-all duration-300 ${
                        toast.type === 'success' 
                            ? 'bg-green-500 text-white' 
                            : 'bg-red-500 text-white'
                    }`}>
                        <div className="flex items-center space-x-2 md:space-x-2 sm:space-x-1">
                            {toast.type === 'success' ? (
                                <svg className="w-5 h-5 md:w-4 md:h-4 sm:w-3.5 sm:h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                </svg>
                            ) : (
                                <svg className="w-5 h-5 md:w-4 md:h-4 sm:w-3.5 sm:h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            )}
                            <span className="font-medium text-sm md:text-sm sm:text-xs">{toast.message}</span>
                        </div>
                    </div>
                )}
                
                {/* Responsive 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">
                        <div className="flex items-center space-x-6 lg:space-x-6 md:space-x-4 sm:space-x-3 xs:space-x-2">
                            {/* Logo and Divider */}
                            <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 in ViolationDetail:', 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 in ViolationDetail:', 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="flex items-center space-x-4 lg:space-x-4 md:space-x-3 sm:space-x-2 xs:space-x-1">
                                {/* Back Arrow and Page Title */}
                                <Button variant="ghost" onClick={handleBackToList} className="p-2 md:p-2 sm:p-1.5 hover:bg-gray-100">
                                    <img 
                                        src={getImagePath("left-arrow-icon.svg")} 
                                        alt="Back" 
                                        className="w-2 h-2 md:w-2 md:h-2 sm:w-1.5 sm:h-1.5"
                                        onError={(e) => {
                                            console.error('Back arrow failed to load:', e.target.src);
                                            // Try fallback path
                                            if (e.target.src !== '/image/left-arrow-icon.svg') {
                                                e.target.src = '/image/left-arrow-icon.svg';
                                            }
                                        }}
                                        onLoad={() => {
                                            console.log('Back arrow loaded successfully:', getImagePath("left-arrow-icon.svg"));
                                        }}
                                    />
                                </Button>
                                <h2 className="text-base md:text-base sm:text-sm font-semibold text-gray-600 font-inter">Violation Detail</h2>
                            </div>
                        </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 in ViolationDetail:', 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 in ViolationDetail:', 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>
                </header>

                {/* Main Content - Responsive Layout */}
                <div className="flex-1 p-4 lg:p-4 md:p-3 sm:p-2 xs:p-1 space-y-2 lg:space-y-2 md:space-y-2 sm:space-y-1 xs:space-y-1 mt-16 lg:mt-16 md:mt-12 sm:mt-10 xs:mt-8 bg-white font-inter flex flex-col">

                    {isLoading ? (
                        <div className="flex items-center justify-center h-64 md:h-56 sm:h-48">
                            <div className="text-center">
                                <div className="animate-spin rounded-full h-12 w-12 md:h-10 md:w-10 sm:h-8 sm:w-8 border-b-2 border-blue-600 mx-auto mb-4 md:mb-3 sm:mb-2"></div>
                                <p className="text-gray-600 md:text-sm sm:text-xs">Loading violation details...</p>
                                {!id && !initialViolation?.id && (
                                    <p className="text-gray-500 text-xs mt-2">Waiting for violation ID...</p>
                                )}
                            </div>
                        </div>
                    ) : !violation ? (
                        <div className="flex items-center justify-center h-64 md:h-56 sm:h-48">
                            <div className="text-center">
                                <p className="text-gray-600 md:text-sm sm:text-xs">
                                    {!id && !initialViolation?.id 
                                        ? "No violation ID provided" 
                                        : "Violation not found or failed to load"
                                    }
                                </p>
                                <div className="flex gap-2 mt-4 md:mt-3 sm:mt-2 justify-center">
                                    <Button 
                                        onClick={handleRetry}
                                        className="bg-blue-600 hover:bg-blue-700"
                                    >
                                        {!id && !initialViolation?.id ? "Go to Dashboard" : "Retry"}
                                    </Button>
                                    <Button onClick={() => navigate('/dashboard')} variant="outline">
                                        Back to Dashboard
                                    </Button>
                                </div>
                            </div>
                        </div>
                    ) : (
                        <div className="grid grid-cols-1 lg:grid-cols-10 gap-4 md:gap-3 sm:gap-2 w-full flex-grow">
                            {/* Left Column - Large Violation Image and License Plate */}
                            <div className="lg:col-span-5 md:col-span-10 sm:col-span-10 space-y-4 md:space-y-3 sm:space-y-2">

                                {/* License Plate Section */}
                                <div>
                                    <h3 className="text-lg md:text-base sm:text-sm font-semibold text-gray-700 mb-6 md:mb-5 sm:mb-4 font-inter text-left">License Plate</h3>
                                    <div className="w-full max-w-[202px] md:max-w-[182px] sm:max-w-[162px] mx-auto border-2 border-gray-300 rounded-lg p-1">
                                        <div className="aspect-[3/1] bg-gray-100 rounded-md flex items-center justify-center overflow-hidden border border-gray-200">
                                            {licensePlateImageUrl && !licensePlateImageError ? (
                                                <img
                                                    src={licensePlateImageUrl}
                                                    alt="License Plate"
                                                    className="w-full h-full object-contain"
                                                    onLoad={() => {
                                                        // Image loaded successfully
                                                        setLicensePlateImageError(false);
                                                    }}
                                                    onError={(e) => {
                                                        console.error('License plate crop image failed to load:', licensePlateImageUrl);
                                                        setLicensePlateImageError(true);
                                                    }}
                                                />
                                            ) : (
                                                <div className="flex items-center justify-center text-gray-500">
                                                    <span className="text-sm">No License Plate Available</span>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>

                                {/* Spacing between License Plate and Violation Image */}
                                <div className="h-8 md:h-6 sm:h-4"></div>

                                {/* Large Violation Image */}
                                <div className="text-center border-2 border-gray-100">
                                    <div className="relative overflow-hidden rounded-lg w-full mx-auto">

                                        <img
                                            ref={(img) => {
                                                if (img) {
                                                    // Store image reference for calculations
                                                    img.onload = () => {
                                                        // Calculate zoom factor when image loads
                                                        const containerWidth = img.parentElement.offsetWidth;
                                                        const containerHeight = img.parentElement.offsetHeight;
                                                        const imageAspectRatio = img.naturalWidth / img.naturalHeight;

                                                        // Calculate how much the image is scaled
                                                        const scaleX = containerWidth / img.naturalWidth;
                                                        const scaleY = containerHeight / img.naturalHeight;
                                                        const scale = Math.min(scaleX, scaleY);

                                                        // Calculate actual displayed image dimensions
                                                        const displayedWidth = img.naturalWidth * scale;
                                                        const displayedHeight = img.naturalHeight * scale;

                                                        // Calculate image positioning within container (centering)
                                                        const offsetX = (containerWidth - displayedWidth) / 2;
                                                        const offsetY = (containerHeight - displayedHeight) / 2;

                                                        // Store all dimensions and offsets for magnifier calculations
                                                        img.dataset.scale = scale;
                                                        img.dataset.containerWidth = containerWidth;
                                                        img.dataset.containerHeight = containerHeight;
                                                        img.dataset.naturalWidth = img.naturalWidth;
                                                        img.dataset.naturalHeight = img.naturalHeight;
                                                        img.dataset.displayedWidth = displayedWidth;
                                                        img.dataset.displayedHeight = displayedHeight;
                                                        img.dataset.offsetX = offsetX;
                                                        img.dataset.offsetY = offsetY;


                                                    };
                                                }
                                            }}
                                            src={imageUrl}
                                            alt={`Evidence for violation #${violation?.id}`}
                                            className="rounded-lg w-full h-[320px] md:h-[280px] sm:h-[240px] max-h-[600px] object-contain mx-auto cursor-pointer"
                                            onLoad={() => {
                                                // Image loaded successfully
                                            }}
                                            onError={(e) => {
                                                console.error('Image failed to load:', imageUrl);
                                                // Try fallback to a static image from public folder
                                                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';
                                                }
                                            }}
                                            onMouseMove={(e) => {
                                                const img = e.currentTarget;
                                                const rect = img.getBoundingClientRect();

                                                // Get mouse position relative to the image container
                                                const containerX = e.clientX - rect.left;
                                                const containerY = e.clientY - rect.top;

                                                // Get stored image data with fallbacks
                                                const offsetX = parseFloat(img.dataset.offsetX) || 0;
                                                const offsetY = parseFloat(img.dataset.offsetY) || 0;
                                                const displayedWidth = parseFloat(img.dataset.displayedWidth) || rect.width;
                                                const displayedHeight = parseFloat(img.dataset.displayedHeight) || rect.height;

                                                // If we don't have proper image dimensions, use a simple approach
                                                if (!img.dataset.naturalWidth || !img.dataset.naturalHeight) {
                                                    // Simple fallback - just show magnifier at mouse position
                                                    setMagnifierPosition({
                                                        x: containerX,
                                                        y: containerY,
                                                        imageX: containerX,
                                                        imageY: containerY
                                                    });
                                                    setShowMagnifier(true);
                                                    return;
                                                }

                                                // Calculate mouse position relative to the actual displayed image (not container)
                                                const imageX = containerX - offsetX;
                                                const imageY = containerY - offsetY;

                                                // Check if mouse is within the actual image bounds
                                                if (imageX < 0 || imageX > displayedWidth || imageY < 0 || imageY > displayedHeight) {
                                                    setShowMagnifier(false);
                                                    return;
                                                }

                                                // Ensure we're getting pixel-perfect positioning
                                                const pixelX = Math.round(imageX);
                                                const pixelY = Math.round(imageY);

                                                // For the lens position, use the actual mouse position (not constrained to container bounds)
                                                // This ensures the lens follows your mouse exactly
                                                const lensX = containerX;
                                                const lensY = containerY;

                                                // Store both container position (for lens) and image position (for zoom calculation)
                                                setMagnifierPosition({
                                                    x: lensX,
                                                    y: lensY,
                                                    imageX: pixelX,
                                                    imageY: pixelY
                                                });
                                                setShowMagnifier(true);


                                            }}
                                            onMouseLeave={() => {
                                                setShowMagnifier(false);
                                            }}
                                        />
                                        {showMagnifier && magnifierPosition && (() => {
                                            // Get the actual image element that's being hovered
                                            const img = document.querySelector('img[src*="' + getImageUrl(violation).split('/').pop() + '"]');
                                            if (!img) {

                                                return null;
                                            }

                                            // Get image dimensions from dataset or natural dimensions
                                            const naturalWidth = parseInt(img.dataset.naturalWidth) || img.naturalWidth || 1000;
                                            const naturalHeight = parseInt(img.dataset.naturalHeight) || img.naturalHeight || 1000;

                                            // Calculate the zoom factor
                                            const zoomFactor = 1.2; // 1.2x zoom

                                            // Use the image coordinates for accurate zoom positioning
                                            const imageX = magnifierPosition.imageX || 0;
                                            const imageY = magnifierPosition.imageY || 0;

                                            // Get the actual displayed image dimensions and offsets
                                            const displayedWidth = parseFloat(img.dataset.displayedWidth) || img.offsetWidth;
                                            const displayedHeight = parseFloat(img.dataset.displayedHeight) || img.offsetHeight;
                                            const offsetX = parseFloat(img.dataset.offsetX) || 0;
                                            const offsetY = parseFloat(img.dataset.offsetY) || 0;

                                            // Calculate the area to crop from the original image
                                            // We want to show a 128x128 pixel area (lens size) zoomed 3x
                                            const cropSize = 128 / zoomFactor; // 42.67 pixels from original image

                                            // Convert displayed coordinates back to natural image coordinates
                                            const naturalX = (imageX / displayedWidth) * naturalWidth;
                                            const naturalY = (imageY / displayedHeight) * naturalHeight;

                                            // Calculate crop position in natural image coordinates
                                            const cropX = naturalX - (cropSize / 2);
                                            const cropY = naturalY - (cropSize / 2);



                                            // Try to use the actual image element's src for better compatibility
                                            const actualImageSrc = img.src || getImageUrl(violation);



                                            return (
                                                <div
                                                    className="absolute w-32 h-32 rounded-full shadow-2xl pointer-events-none z-10 transition-all duration-200 ease-out overflow-hidden"
                                                    style={{
                                                        left: `${magnifierPosition.x - 64}px`,
                                                        top: `${magnifierPosition.y - 64}px`,
                                                        boxShadow: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)'
                                                    }}
                                                >
                                                    <img
                                                        src={actualImageSrc}
                                                        alt="Magnified view"
                                                        className="w-full h-full"
                                                        style={{
                                                            width: '128px',
                                                            height: '128px',
                                                            objectPosition: `${-cropX}px ${-cropY}px`,
                                                            objectFit: 'none',
                                                            imageRendering: 'crisp-edges',
                                                            transform: 'scale(1)',
                                                            backfaceVisibility: 'hidden'
                                                        }}
                                                        onError={(e) => {
                                                            console.error('Magnifier image failed to load:', actualImageSrc);
                                                            e.target.style.display = 'none';
                                                        }}
                                                    />
                                                </div>
                                            );
                                        })()}
                                    </div>
                                </div>

                            </div>

                            {/* Right Column - Scrollable Cards Container */}
                            <div className="lg:col-span-5 md:col-span-10 sm:col-span-10">
                                <div className="space-y-4 md:space-y-3 sm:space-y-2 max-h-[calc(100vh-120px)] overflow-y-auto pr-2">
                                    <div className="w-full max-w-[420px] md:max-w-full sm:max-w-full">
                                        <Card className="shadow-lg border-2 border-gray-100">
                                            <CardContent className="p-5 md:p-4 sm:p-3">
                                                <div className="flex items-center justify-between mb-3">
                                                    <CardTitle className="font-inter text-sm md:text-sm sm:text-xs">Violation Details</CardTitle>
                                                    {violation?.challan_status && (
                                                        <Badge className={`${violation.challan_status.toLowerCase() === 'new'
                                                            ? 'bg-blue-100 text-blue-800 border-blue-200'
                                                            : violation.challan_status.toLowerCase() === 'raised'
                                                                ? 'bg-green-100 text-green-800 border-green-200'
                                                                : violation.challan_status.toLowerCase() === 'rejected'
                                                                    ? 'bg-red-100 text-red-800 border-red-200'
                                                                    : 'bg-gray-100 text-gray-800 border-gray-200'
                                                            } hover:bg-opacity-80 text-xs`}>
                                                            {violation.challan_status}
                                                        </Badge>
                                                    )}
                                                </div>

                                                <div className="space-y-3">
                                                    {/* Vehicle Number */}
                                                    <div className="space-y-2">
                                                        <span className="font-medium text-xs md:text-xs sm:text-xs">Vehicle number</span>
                                                        <div className="relative">
                                                            {isEditingPlate ? (
                                                                <Input
                                                                    value={newPlateNumber}
                                                                    onChange={(e) => setNewPlateNumber(e.target.value.toUpperCase())}
                                                                    className="font-mono h-6 md:h-6 sm:h-5 pr-8 text-xs md:text-xs sm:text-xs bg-white border border-blue-500 ring-1 ring-blue-500 rounded-md"
                                                                    disabled={isSubmitting}
                                                                    maxLength={20}
                                                                    placeholder="Enter vehicle number"
                                                                    autoFocus
                                                                />
                                                            ) : (
                                                                <div className="h-6 md:h-6 sm:h-5 px-2 py-1 bg-gray-50 border border-gray-300 rounded-md flex items-center justify-between">
                                                                    <span className="font-mono text-xs md:text-xs sm:text-xs text-gray-700">
                                                                        {violation?.license_plate_number || 'No plate number'}
                                                                    </span>
                                                                    {violation?.challan_status?.toLowerCase() === 'new' ? (
                                                                        <Button
                                                                            type="button"
                                                                            size="icon"
                                                                            variant="ghost"
                                                                            className="h-4 w-4 md:h-4 md:w-4 sm:h-3 sm:w-3 hover:bg-gray-100"
                                                                            onClick={(e) => {
                                                                                e.preventDefault();
                                                                                e.stopPropagation();
                                                                                setIsEditingPlate(true);
                                                                                setNewPlateNumber(violation?.license_plate_number || '');
                                                                            }}
                                                                        >
                                                                            <Pencil className="h-2 w-2 md:h-2 md:w-2 sm:h-1.5 sm:w-1.5 text-gray-500" />
                                                                        </Button>
                                                                    ) : (
                                                                        <div className="h-4 w-4 md:h-4 md:w-4 sm:h-3 sm:w-3 flex items-center justify-center">
                                                                            <div className="h-2 w-2 md:h-2 md:w-2 sm:h-1.5 sm:w-1.5 bg-gray-300 rounded-full"></div>
                                                                        </div>
                                                                    )}
                                                                </div>
                                                            )}
                                                            {isEditingPlate && (
                                                                <div className="absolute right-1 top-1/2 transform -translate-y-1/2 flex gap-1">
                                                                    <Button
                                                                        type="button"
                                                                        size="icon"
                                                                        variant="ghost"
                                                                        className="h-4 w-4 md:h-4 md:w-4 sm:h-3 sm:w-3 hover:bg-green-100 text-green-600"
                                                                        onClick={handleUpdatePlate}
                                                                        disabled={isSubmitting}
                                                                    >
                                                                        {isSubmitting ? (
                                                                            <div className="animate-spin rounded-full h-2 w-2 md:h-2 md:w-2 sm:h-1.5 sm:w-1.5 border-b border-green-600"></div>
                                                                        ) : (
                                                                            <CheckCircle className="h-2 w-2 md:h-2 md:w-2 sm:h-1.5 sm:w-1.5" />
                                                                        )}
                                                                    </Button>
                                                                    <Button
                                                                        type="button"
                                                                        size="icon"
                                                                        variant="ghost"
                                                                        className="h-4 w-4 md:h-4 md:w-4 sm:h-3 sm:w-3 hover:bg-red-100 text-red-600"
                                                                        onClick={() => {
                                                                            setIsEditingPlate(false);
                                                                            setNewPlateNumber(violation?.license_plate_number || '');
                                                                        }}
                                                                        disabled={isSubmitting}
                                                                    >
                                                                        <X className="h-2 w-2 md:h-2 md:w-2 sm:h-1.5 sm:w-1.5" />
                                                                    </Button>
                                                                </div>
                                                            )}
                                                        </div>
                                                    </div>
                                                    {/* Violation Types */}
                                                    <div className="space-y-2">
                                                        <span className="font-medium text-xs md:text-xs sm:text-xs">Violation type</span>


                                                        {/* Current Violation Types Display */}
                                                        <div className="relative violation-types-container">
                                                            <div
                                                                className={`min-h-[20px] bg-white border border-gray-300 rounded-md p-0.5 flex flex-wrap gap-0.5 items-center transition-colors ${isUpdatingViolationTypes
                                                                        ? 'cursor-not-allowed opacity-50'
                                                                        : violation?.challan_status?.toLowerCase() === 'new'
                                                                            ? 'cursor-pointer hover:border-gray-400'
                                                                            : 'cursor-default'
                                                                    }`}
                                                                onClick={() => {
                                                                    if (isUpdatingViolationTypes) return;
                                                                    if (violation?.challan_status?.toLowerCase() !== 'new') return;
                                                                    if (!showViolationTypesDropdown) {
                                                                        setViolationTypeSearch(''); // Clear search when opening
                                                                    }
                                                                    setShowViolationTypesDropdown(!showViolationTypesDropdown);
                                                                }}
                                                            >
                                                                {(() => {
                                                                    try {
                                                                        const types = violation?.violation_types ? JSON.parse(violation.violation_types) : [];
                                                                        const violationTypes = Array.isArray(types) ? types : [types].filter(Boolean);

                                                                        if (violationTypes.length === 0) {
                                                                            return <span className="text-gray-500 text-xs">-</span>;
                                                                        }

                                                                        // Show all violation types
                                                                        return violationTypes.map((type, index) => (
                                                                            <div key={index} className="flex items-center gap-0.5 bg-red-100 text-red-800 border border-red-300 text-xs md:text-xs sm:text-xs px-1 py-0.5 rounded-md">
                                                                                {type}
                                                                                {isUpdatingViolationTypes ? (
                                                                                    <div className="animate-spin rounded-full h-2 w-2 md:h-2 md:w-2 sm:h-1.5 sm:w-1.5 border-b border-red-600"></div>
                                                                                ) : violation?.challan_status?.toLowerCase() === 'new' ? (
                                                                                    <X
                                                                                        className="h-2 w-2 md:h-2 md:w-2 sm:h-1.5 sm:w-1.5 cursor-pointer text-red-600 hover:text-red-800"
                                                                                        onClick={(e) => {
                                                                                            e.stopPropagation();
                                                                                            handleRemoveViolationType(type);
                                                                                        }}
                                                                                    />
                                                                                ) : (
                                                                                    <div className="h-2 w-2 md:h-2 md:w-2 sm:h-1.5 sm:w-1.5 bg-gray-300 rounded-full"></div>
                                                                                )}
                                                                            </div>
                                                                        ));
                                                                    } catch (error) {
                                                                        return <span className="text-gray-500 text-xs">-</span>;
                                                                    }
                                                                })()}
                                                            </div>

                                                            {/* Dropdown Indicator */}
                                                            <div className="absolute right-2 top-1/2 transform -translate-y-1/2 pointer-events-none">
                                                                <svg className={`w-4 h-4 md:w-4 md:h-4 sm:w-3 sm:h-3 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>
                                                            </div>

                                                            {/* Dropdown Menu */}
                                                            {showViolationTypesDropdown && (
                                                                <div className="absolute top-full left-0 right-0 mt-1 bg-white border border-gray-300 rounded-md shadow-lg z-50 max-h-[258px] overflow-y-auto">
                                                                    {/* Search Input */}
                                                                    <div className="sticky top-0 bg-white border-b border-gray-200 p-2">
                                                                        <Input
                                                                            type="text"
                                                                            placeholder="Search violation types..."
                                                                            value={violationTypeSearch}
                                                                            onChange={(e) => setViolationTypeSearch(e.target.value)}
                                                    className="h-8 md:h-7 sm:h-6 text-xs md:text-xs sm:text-xs border-gray-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-500"
                                                                            onClick={(e) => e.stopPropagation()}
                                                                        />
                                                                    </div>

                                                                    {/* Filtered Violation Types List */}
                                                                    {isLoadingViolationTypes ? (
                                                                        <div className="px-3 py-4 text-sm md:text-sm sm:text-xs text-gray-500 text-center">
                                                                            Loading violation types...
                                                                        </div>
                                                                    ) : (Array.isArray(allViolationTypes) && allViolationTypes.length > 0) || (typeof allViolationTypes === 'object' && allViolationTypes !== null && Object.keys(allViolationTypes).length > 0) ? (
                                                                        <>
                                                                            {/* Current Violation Types Section */}
                                                                            {(() => {
                                                                                // Get current violation types for this violation
                                                                                let currentTypes = [];
                                                                                try {
                                                                                    currentTypes = violation?.violation_types ? JSON.parse(violation.violation_types) : [];
                                                                                    currentTypes = Array.isArray(currentTypes) ? currentTypes : [currentTypes].filter(Boolean);
                                                                                } catch (error) {
                                                                                    currentTypes = Array.isArray(violation?.violation_types) ? violation.violation_types : [violation?.violation_types].filter(Boolean);
                                                                                }

                                                                                if (currentTypes.length > 0) {
                                                                                    return (
                                                                                        <>
                                                                                            <div className="px-3 py-2 text-xs md:text-xs sm:text-xs font-semibold text-gray-700 bg-gray-100 border-b border-gray-200">
                                                                                                Current Violation Types
                                                                                            </div>
                                                                                            {currentTypes.map((type) => (
                                                                                                <div
                                                                                                    key={type}
                                                                                                    className={`px-3 py-2 text-sm md:text-sm sm:text-xs text-gray-700 border-b border-gray-100 last:border-b-0 bg-green-50 ${isUpdatingViolationTypes
                                                                                                            ? 'cursor-not-allowed opacity-50'
                                                                                                            : 'hover:bg-gray-100 cursor-pointer'
                                                                                                        }`}
                                                                                                    onClick={() => {
                                                                                                        if (isUpdatingViolationTypes) return;
                                                                                                        handleAddViolationType(type);
                                                                                                        setShowViolationTypesDropdown(false);
                                                                                                        setViolationTypeSearch(''); // Clear search when selecting
                                                                                                    }}
                                                                                                >
                                                                                                    <span className="text-green-700">✓ {type}</span>
                                                                                                </div>
                                                                                            ))}
                                                                                        </>
                                                                                    );
                                                                                }
                                                                                return null;
                                                                            })()}

                                                                            {/* Available Violation Types Section - Category-wise */}
                                                                            {(() => {
                                                                                if (Array.isArray(allViolationTypes)) {
                                                                                    // Flat array structure
                                                                                    const availableTypes = allViolationTypes.filter(type => {
                                                                                        try {
                                                                                            const types = violation?.violation_types ? JSON.parse(violation.violation_types) : [];
                                                                                            const violationTypes = Array.isArray(types) ? types : [types].filter(Boolean);
                                                                                            return !violationTypes.includes(type) &&
                                                                                                type.toLowerCase().includes(violationTypeSearch.toLowerCase());
                                                                                        } catch (error) {
                                                                                            return type.toLowerCase().includes(violationTypeSearch.toLowerCase());
                                                                                        }
                                                                                    });

                                                                                    if (availableTypes.length > 0) {
                                                                                        return (
                                                                                            <>
                                                                                                                                                                                            <div className="px-3 py-2 text-xs md:text-xs sm:text-xs font-semibold text-gray-700 bg-gray-100 border-b border-gray-200">
                                                                                                    Available Violation Types
                                                                                                </div>
                                                                                                {availableTypes.map((type) => (
                                                                                                    <div
                                                                                                        key={type}
                                                                                                        className={`px-3 py-2 text-sm md:text-sm sm:text-xs text-gray-700 border-b border-gray-100 last:border-b-0 ${isUpdatingViolationTypes
                                                                                                                ? 'cursor-not-allowed opacity-50'
                                                                                                                : 'hover:bg-gray-100 cursor-pointer'
                                                                                                            }`}
                                                                                                        onClick={() => {
                                                                                                            if (isUpdatingViolationTypes) return;
                                                                                                            handleAddViolationType(type);
                                                                                                            setShowViolationTypesDropdown(false);
                                                                                                            setViolationTypeSearch(''); // Clear search when selecting
                                                                                                        }}
                                                                                                    >
                                                                                                        {type}
                                                                                                    </div>
                                                                                                ))}
                                                                                            </>
                                                                                        );
                                                                                    }
                                                                                } else if (typeof allViolationTypes === 'object' && allViolationTypes !== null) {
                                                                                    // Category-based structure
                                                                                    return Object.entries(allViolationTypes).map(([category, violations]) => {
                                                                                        // Filter violations in this category based on search
                                                                                        let filteredViolations = [];
                                                                                        if (Array.isArray(violations)) {
                                                                                            filteredViolations = violations.filter(violationType => {
                                                                                                try {
                                                                                                    const types = violation?.violation_types ? JSON.parse(violation.violation_types) : [];
                                                                                                    const currentTypes = Array.isArray(types) ? types : [types].filter(Boolean);
                                                                                                    return !currentTypes.includes(violationType) &&
                                                                                                        violationType.toLowerCase().includes(violationTypeSearch.toLowerCase());
                                                                                                } catch (error) {
                                                                                                    return violationType.toLowerCase().includes(violationTypeSearch.toLowerCase());
                                                                                                }
                                                                                            });
                                                                                        } else if (typeof violations === 'string') {
                                                                                            try {
                                                                                                const types = violation?.violation_types ? JSON.parse(violation.violation_types) : [];
                                                                                                const currentTypes = Array.isArray(types) ? types : [types].filter(Boolean);
                                                                                                if (!currentTypes.includes(violations) &&
                                                                                                    violations.toLowerCase().includes(violationTypeSearch.toLowerCase())) {
                                                                                                    filteredViolations = [violations];
                                                                                                }
                                                                                            } catch (error) {
                                                                                                if (violations.toLowerCase().includes(violationTypeSearch.toLowerCase())) {
                                                                                                    filteredViolations = [violations];
                                                                                                }
                                                                                            }
                                                                                        }

                                                                                        if (filteredViolations.length > 0) {
                                                                                            return (
                                                                                                <div key={category}>
                                                                                                    {/* Category Header */}
                                                                <div className="px-3 py-2 text-xs md:text-xs sm:text-xs font-semibold text-gray-700 bg-gray-100 border-b border-gray-200">
                                                                                                        {category}
                                                                                                    </div>
                                                                                                    {/* Violation Types in this category */}
                                                                                                    {filteredViolations.map((violationType, index) => (
                                                                                                        <div
                                                                                                            key={`${category}-${index}`}
                                                                                                            className={`px-3 py-2 text-sm md:text-sm sm:text-xs text-gray-700 border-b border-gray-100 last:border-b-0 pl-4 ${isUpdatingViolationTypes
                                                                                                                    ? 'cursor-not-allowed opacity-50'
                                                                                                                    : 'hover:bg-gray-100 cursor-pointer'
                                                                                                                }`}
                                                                                                            onClick={() => {
                                                                                                                if (isUpdatingViolationTypes) return;
                                                                                                                handleAddViolationType(violationType);
                                                                                                                setShowViolationTypesDropdown(false);
                                                                                                                setViolationTypeSearch(''); // Clear search when selecting
                                                                                                            }}
                                                                                                        >
                                                                                                            {violationType}
                                                                                                        </div>
                                                                                                    ))}
                                                                                                </div>
                                                                                            );
                                                                                        }
                                                                                        return null;
                                                                                    });
                                                                                }
                                                                                return null;
                                                                            })()}
                                                                        </>
                                                                    ) : (
                                                                        <div className="px-3 py-4 text-sm md:text-sm sm:text-xs text-gray-500 text-center">
                                                                            {allViolationTypes.length === 0 ? 'No violation types available' : 'No violation types found'}
                                                                        </div>
                                                                    )}
                                                                </div>
                                                            )}
                                                        </div>


                                                    </div>

                                                    {/* Location and Time */}
                                                    <div className="space-y-2">
                                                        <span className="font-medium text-xs md:text-xs sm:text-xs">Location and Time</span>
                                                        <div className="space-y-2 text-xs md:text-xs sm:text-xs text-gray-600">
                                                            <div>{violation?.location_text || '-'}</div>
                                                            <div>{violation?.timestamp ? format(new Date(violation.timestamp + 'Z'), 'dd - MMM - yyyy | hh:mm a') : '-'}</div>
                                                        </div>
                                                    </div>

                                                    {/* Vehicle Details */}
                                                    <div className="space-y-3">
                                                        <span className="font-medium text-xs md:text-xs sm:text-xs">Vehicle Details</span>
                                                        <div className="border border-gray-200 rounded-md overflow-hidden">
                                                            <table className="w-full text-xs md:text-xs sm:text-xs">
                                                                <tbody>
                                                                    <tr className="border-b border-gray-100">
                                                                        <td className="px-2 py-1 text-gray-600 font-medium bg-gray-50 text-xs md:text-xs sm:text-xs">Type</td>
                                                                        <td className="px-2 py-1 text-xs md:text-xs sm:text-xs">{violation?.vehicle?.vehicle_type || '-'}</td>
                                                                    </tr>
                                                                    <tr className="border-b border-gray-100">
                                                                        <td className="px-2 py-1 text-gray-600 font-medium bg-gray-50 text-xs md:text-xs sm:text-xs">Maker</td>
                                                                        <td className="px-2 py-1 text-xs md:text-xs sm:text-xs">{violation?.vehicle?.vehicle_maker || '-'}</td>
                                                                    </tr>
                                                                    <tr className="border-b border-gray-100">
                                                                        <td className="px-2 py-1 text-gray-600 font-medium bg-gray-50 text-xs md:text-xs sm:text-xs">Model</td>
                                                                        <td className="px-1 py-0.5 text-xs md:text-xs sm:text-xs">{violation?.vehicle?.vehicle_model || '-'}</td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td className="px-2 py-1 text-gray-600 font-medium bg-gray-50 text-xs md:text-xs sm:text-xs">Color</td>
                                                                        <td className="px-2 py-1 text-xs md:text-xs sm:text-xs">{violation?.vehicle?.vehicle_color || '-'}</td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                    </div>

                                                    {/* Action Buttons */}
                                                    <div className="space-y-2 pt-5">
                                                        <div className="flex gap-2 md:gap-2 sm:gap-1">
                                                            <Button
                                                                variant="destructive"
                                                                className="flex-1 h-8 md:h-8 sm:h-7 text-sm md:text-sm sm:text-xs"
                                                                onClick={violation?.challan_status?.toLowerCase() === 'rejected' || violation?.challan_status?.toLowerCase() === 'raised' ? undefined : handleRejectChallan}
                                                                disabled={isSubmitting || violation?.challan_status?.toLowerCase() === 'rejected' || violation?.challan_status?.toLowerCase() === 'raised'}
                                                            >
                                                                Reject
                                                            </Button>
                                                            <Button
                                                                className="flex-1 h-8 md:h-8 sm:h-7 text-sm md:text-sm sm:text-xs bg-green-600 hover:bg-green-700"
                                                                onClick={violation?.challan_status?.toLowerCase() === 'raised' || violation?.challan_status?.toLowerCase() === 'rejected' ? undefined : handleRaiseChallan}
                                                                disabled={isSubmitting || violation?.challan_status?.toLowerCase() === 'raised' || violation?.challan_status?.toLowerCase() === 'rejected'}
                                                            >
                                                                Raise
                                                            </Button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </CardContent>
                                        </Card>
                                        {/* Officers Details Card */}
                                        <Card className="shadow-lg border-2 border-gray-100">
                                            <CardContent className="p-5 md:p-4 sm:p-3">
                                                <div className="flex items-center justify-between mb-3">
                                                    <CardTitle className="font-inter text-sm md:text-sm sm:text-xs">Officer Details</CardTitle>
                                                </div>
                                                <div className="space-y-3">
                                                    <div className="space-y-1">
                                                        <span className="font-medium text-xs md:text-xs sm:text-xs">Login ID</span>
                                                        <div className="text-xs md:text-xs sm:text-xs text-gray-600">
                                                            {violation?.officer?.login_id || '-'}
                                                        </div>
                                                    </div>
                                                    <div className="space-y-1">
                                                        <span className="font-medium text-xs md:text-xs sm:text-xs">Name</span>
                                                        <div className="text-xs md:text-xs sm:text-xs text-gray-600">
                                                            {violation?.officer?.name || '-'}
                                                        </div>
                                                    </div>
                                                    <div className="space-y-1">
                                                        <span className="font-medium text-xs md:text-xs sm:text-xs">Mobile number</span>
                                                        <div className="text-xs md:text-xs sm:text-xs text-gray-600">
                                                            {violation?.officer?.mobile || '-'}
                                                        </div>
                                                    </div>
                                                    <div className="space-y-1">
                                                        <span className="font-medium text-xs md:text-xs sm:text-xs">Police station</span>
                                                        <div className="text-xs md:text-xs sm:text-xs text-gray-600">
                                                            {violation?.officer?.police_station || '-'}
                                                        </div>
                                                    </div>
                                                    <div className="space-y-1">
                                                        <span className="font-medium text-xs md:text-xs sm:text-xs">Junction</span>
                                                        <div className="text-xs md:text-xs sm:text-xs text-gray-600">
                                                            {violation?.officer?.junction_name || '-'}
                                                        </div>
                                                    </div>
                                                    <div className="space-y-1">
                                                        <span className="font-medium text-xs md:text-xs sm:text-xs">Device ID</span>
                                                        <div className="text-xs md:text-xs sm:text-xs text-gray-600">
                                                            {violation?.device_id || '-'}
                                                        </div>
                                                    </div>
                                                </div>
                                            </CardContent>
                                        </Card>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}


                </div>

                {/* Footer */}
                <div className="bg-white px-4 md:px-3 sm:px-2 py-2 text-left text-sm md:text-sm sm:text-xs text-gray-400 border-t border-gray-200">
                    <p>© 2025 PushpakAI. All rights reserved.</p>
                </div>
            </div>
        </div>
    );
}