import React from 'react';
import { format } from 'date-fns';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { getImagePath } from '../lib/utils';

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

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

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

    return (
        <div className="flex flex-col items-center space-y-2 md:space-y-2 sm:space-y-1 py-4 md:py-4 sm:py-3">
            {/* Page Info */}
            <div className="text-xs text-gray-600">
                Page {paginationInfo.currentPage} of {paginationInfo.totalPages} 
                ({paginationInfo.totalItems} total violations)
            </div>
            
            {/* Pagination Buttons */}
            <div className="flex items-center justify-center space-x-1 md:space-x-1 sm:space-x-0.5">
                <button
                    onClick={() => onPageChange(paginationInfo.currentPage - 1)}
                    disabled={!paginationInfo.hasPrev}
                    className={`w-6 h-6 md:w-6 md:h-6 sm:w-5 sm:h-5 rounded-sm border text-xs font-medium transition-colors ${!paginationInfo.hasPrev
                        ? 'bg-gray-100 text-gray-400 cursor-not-allowed border-gray-200'
                        : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-200'
                        }`}
                >
                    ‹
                </button>

                {(() => {
                    const pages = [];
                    
                    // Always show first two pages
                    for (let i = 1; i <= Math.min(2, paginationInfo.totalPages); i++) {
                        pages.push(
                            <button
                                key={i}
                                onClick={() => onPageChange(i)}
                                className={`w-6 h-6 rounded-sm border text-xs font-medium transition-colors ${paginationInfo.currentPage === i
                                    ? 'bg-blue-600 text-white border-blue-600'
                                    : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-200'
                                    }`}
                            >
                                {i}
                            </button>
                        );
                    }
                    
                    // Add ellipsis if there are more than 4 pages
                    if (paginationInfo.totalPages > 4) {
                        pages.push(
                            <span key="ellipsis" className="w-6 h-6 flex items-center justify-center text-xs text-gray-600 border border-gray-200 rounded-sm">
                                ...
                            </span>
                        );
                    }
                    
                    // Show last two pages (if different from first two)
                    if (paginationInfo.totalPages > 2) {
                        for (let i = Math.max(3, paginationInfo.totalPages - 1); i <= paginationInfo.totalPages; i++) {
                            if (i > 2) { // Avoid duplicate pages
                                pages.push(
                                    <button
                                        key={i}
                                        onClick={() => onPageChange(i)}
                                        className={`w-6 h-6 rounded-sm border text-xs font-medium transition-colors ${paginationInfo.currentPage === i
                                            ? 'bg-blue-600 text-white border-blue-600'
                                            : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-200'
                                            }`}
                                    >
                                        {i}
                                    </button>
                                );
                            }
                        }
                    }
                    
                    return pages;
                })()}

                <button
                    onClick={() => onPageChange(paginationInfo.currentPage + 1)}
                    disabled={!paginationInfo.hasNext}
                    className={`w-6 h-6 rounded-sm border text-xs font-medium transition-colors ${!paginationInfo.hasNext
                        ? 'bg-gray-100 text-gray-400 cursor-not-allowed border-gray-200'
                        : 'bg-white text-gray-600 hover:bg-gray-50 border-gray-200'
                        }`}
                >
                    ›
                </button>
            </div>
        </div>
    );
}

export function ViolationList({ 
    violations = [], 
    onSelectViolation, 
    isLoading = false,
    paginationInfo = null,
    onPageChange = null,
    currentPage = 1,
    pageSize = 20,
    className = ""
}) {
    if (isLoading) {
        return (
            <div className="w-full overflow-x-auto border border-gray-200 rounded-lg" style={{ minWidth: 'fit-content' }}>
                <Table className="min-w-full text-xs" style={{ tableLayout: 'fixed' }}>
                    <TableHeader>
                        <TableRow>
                            <TableHead className="w-12 min-w-[3rem] text-xs px-2">Sl.No</TableHead>
                            <TableHead className="w-20 min-w-[5rem] text-xs px-2">Image</TableHead>
                            <TableHead className="w-24 min-w-[6rem] text-xs px-2">ID</TableHead>
                            <TableHead className="w-20 min-w-[5rem] text-xs px-2">Status</TableHead>
                            <TableHead className="w-28 min-w-[7rem] text-xs px-2">License plate</TableHead>
                            <TableHead className="w-64 min-w-[16rem] text-xs px-2">Violation</TableHead>
                            <TableHead className="w-20 min-w-[5rem] text-xs px-2">Location</TableHead>
                            <TableHead className="w-32 min-w-[8rem] text-xs px-2">Time</TableHead>
                        </TableRow>
                    </TableHeader>
                    <TableBody>
                        <TableRow>
                            <TableCell colSpan="8" className="h-12 text-center text-xs py-1 px-2">Loading violations...</TableCell>
                        </TableRow>
                    </TableBody>
                </Table>
            </div>
        );
    }

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

            {/* Custom Server-Side Pagination */}
            {paginationInfo && onPageChange && (
                <ServerPagination
                    paginationInfo={paginationInfo}
                    onPageChange={onPageChange}
                />
            )}
        </div>
    );
}