import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Users, Search, Star, Calendar, UserCheck, UserX, Plus, MapPin, Building2, Briefcase, FileText, Clock, MoreVertical, LogOut, BarChart3 } from 'lucide-react';

import Table, { Column } from '../../components/UI/Table';
import Pagination from '../../components/UI/Pagination';
import ButtonUI from '../../components/UI/ButtonUI';
import AddTrainerModal, { TrainerFormData } from '../../modal/TrainersAvailability/AddTrainerModal';
import LeaveSubstitutionModal from '../../modal/TrainersAvailability/LeaveSubstitutionModal';
import ExitTrainerModal from '../../modal/TrainersAvailability/ExitTrainerModal';
import { useToast, ToastContainer } from '../../components/UI/Toast';
import ActionButtons from '../../components/UI/ActionButtons';
import ConfirmationModal from '../../modal/ConfirmationModal';
import TrainerAnalysisModal from '../../modal/TrainersAvailability/TrainerAnalysisModal';

interface Trainer {
    id: string;
    name: string;
    initials: string;
    subjects: string[];
    type: 'In-house' | 'Visiting';
    utilization: number;
    rating: number;
    branch: string;
    phone: string;
    email: string;
    avatarColor: string;
    experience?: number;
    certifications?: string[];
    rate?: string;
    availability?: {
        monday: boolean;
        tuesday: boolean;
        wednesday: boolean;
        thursday: boolean;
        friday: boolean;
        saturday: boolean;
        sunday: boolean;
    };
    // In-house specific fields (optional for backward compatibility)
    staffCode?: string;
    department?: string;
    role?: string;
    specialization?: string;
    status?: 'Active' | 'Inactive' | 'On Leave';
    joinDate?: string;
    profileImage?: string | null;
    gender?: string;
    dateOfBirth?: string;
    maritalStatus?: string;
    address?: string;
    contactPerson?: string;
    contactPersonMobileNumber?: string;
    alternateMobileNumber?: string;
    qualifications?: Array<{
        qualificationType: string;
        degreeName: string;
        major: string;
        university: string;
    }>;
    subDepartment?: string;
    jobPosition?: string;
    jobType?: string;
    prevPosition?: string;
    yearsOfExperience?: string;
    prevCompany?: string;
    nickName?: string;
    skillTag?: string;
    basicSalary?: string;
    perHourCost?: string;
    username?: string;
    password?: string;
    otherAttachment?: string | null;
    description?: string;
    // Visiting specific fields
    costPerSession?: string;
    skillTags?: string[];
    documents?: Array<{
        name: string;
        file: string | null;
        type: string;
        documentType: string;
    }>;
    isExited?: boolean;
    exitDate?: string;
    exitType?: string;
}

const Trainers = () => {
    const navigate = useNavigate();
    const toast = useToast();
    const [searchTerm, setSearchTerm] = useState('');
    const [currentPage, setCurrentPage] = useState(1);
    const [filterType, setFilterType] = useState<'All' | 'In-house' | 'Visiting'>('All');
    const [showAddModal, setShowAddModal] = useState(false);
    const [showLeaveModal, setShowLeaveModal] = useState(false);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [showExitModal, setShowExitModal] = useState(false);
    const [showAnalysisModal, setShowAnalysisModal] = useState(false);
    const [trainerToDelete, setTrainerToDelete] = useState<Trainer | null>(null);
    const [trainerToExit, setTrainerToExit] = useState<Trainer | null>(null);
    const [selectedTrainerId, setSelectedTrainerId] = useState<string | null>(null);
    const [isDeleting, setIsDeleting] = useState(false);
    const [editingTrainer, setEditingTrainer] = useState<Trainer | null>(null);
    const [showDropdown, setShowDropdown] = useState<string | null>(null);
    const itemsPerPage = 6;

    // Mock trainers data
    const [trainers, setTrainers] = useState<Trainer[]>([
        {
            id: '1',
            name: 'Karthik Raja',
            initials: 'KR',
            subjects: ['Python', 'Java'],
            type: 'In-house',
            utilization: 86,
            rating: 4.6,
            branch: 'Madurai HQ',
            phone: '+91 98431 22014',
            email: 'karthik@upskill365.in',
            avatarColor: '#4338CA',
            experience: 8,
            certifications: ['AWS Certified', 'Python Expert'],
            rate: '₹1,200/hr',
            staffCode: 'ST-001',
            department: 'Training',
            role: 'Senior Trainer',
            specialization: 'Python Full Stack',
            status: 'Active',
            joinDate: '2020-01-15',
            gender: 'Male',
            dateOfBirth: '1988-05-15',
            maritalStatus: 'Married',
            address: '123, Anna Nagar, Madurai - 625020',
            contactPerson: 'Lakshmi Raja',
            contactPersonMobileNumber: '9944049881',
            alternateMobileNumber: '9944049880',
            qualifications: [
                {
                    qualificationType: 'Post Graduate',
                    degreeName: 'M.Sc. Computer Science',
                    major: 'Artificial Intelligence',
                    university: 'Madurai Kamaraj University',
                },
            ],
            basicSalary: '₹45,000',
            perHourCost: '₹1,200',
            username: 'karthik.raja',
            password: 'Password@123',
            description: 'Senior Python trainer with 8+ years of experience in software development and training.',
            availability: {
                monday: true,
                tuesday: true,
                wednesday: true,
                thursday: true,
                friday: true,
                saturday: false,
                sunday: false,
            },
        },
        {
            id: '2',
            name: 'Priya Dharshini',
            initials: 'PD',
            subjects: ['Data Science', 'ML'],
            type: 'In-house',
            utilization: 78,
            rating: 4.4,
            branch: 'Chennai',
            phone: '+91 94425 18876',
            email: 'priya@upskill365.in',
            avatarColor: '#0D9488',
            experience: 5,
            certifications: ['Google Data Analytics'],
            rate: '₹1,100/hr',
            staffCode: 'ST-002',
            department: 'Training',
            role: 'Trainer',
            specialization: 'Data Science & AI',
            status: 'Active',
            joinDate: '2021-06-20',
            gender: 'Female',
            dateOfBirth: '1992-09-10',
            maritalStatus: 'Single',
            address: '78, Adyar, Chennai - 600020',
            contactPerson: 'Ravi Dharshini',
            contactPersonMobileNumber: '9944049890',
            alternateMobileNumber: '9944049890',
            qualifications: [
                {
                    qualificationType: 'Post Graduate',
                    degreeName: 'M.Sc. Data Science',
                    major: 'Machine Learning',
                    university: 'IIT Madras',
                },
            ],
            basicSalary: '₹38,000',
            perHourCost: '₹1,100',
            username: 'priya.dharshini',
            password: 'Password@123',
            description: 'Data Science trainer with expertise in Machine Learning and AI.',
            availability: {
                monday: true,
                tuesday: true,
                wednesday: true,
                thursday: true,
                friday: true,
                saturday: false,
                sunday: false,
            },
        },
        {
            id: '3',
            name: 'Mohamed Aslam',
            initials: 'MA',
            subjects: ['Python', 'Cloud'],
            type: 'In-house',
            utilization: 64,
            rating: 4.5,
            branch: 'Madurai HQ',
            phone: '+91 99947 30281',
            email: 'aslam@upskill365.in',
            avatarColor: '#D97706',
            experience: 6,
            certifications: ['Azure Certified'],
            rate: '₹1,000/hr',
            staffCode: 'ST-003',
            department: 'Training',
            role: 'Trainer',
            specialization: 'Cloud & DevOps',
            status: 'Active',
            joinDate: '2021-03-10',
            gender: 'Male',
            dateOfBirth: '1990-07-20',
            maritalStatus: 'Married',
            address: '45, K.K. Nagar, Madurai - 625020',
            contactPerson: 'Fathima Aslam',
            contactPersonMobileNumber: '9944049889',
            alternateMobileNumber: '9944049889',
            qualifications: [
                {
                    qualificationType: 'Post Graduate',
                    degreeName: 'M.Tech Cloud Computing',
                    major: 'Cloud Architecture',
                    university: 'Anna University',
                },
            ],
            basicSalary: '₹35,000',
            perHourCost: '₹1,000',
            username: 'aslam.mohamed',
            password: 'Password@123',
            description: 'Cloud & DevOps trainer with expertise in Azure and Kubernetes.',
            availability: {
                monday: true,
                tuesday: true,
                wednesday: true,
                thursday: true,
                friday: true,
                saturday: false,
                sunday: false,
            },
        },
        {
            id: '4',
            name: 'Deepa Lakshmi',
            initials: 'DL',
            subjects: ['Soft Skills', 'Aptitude'],
            type: 'Visiting',
            utilization: 52,
            rating: 4.7,
            branch: 'Madurai HQ',
            phone: '+91 96005 71133',
            email: 'deepa@upskill365.in',
            avatarColor: '#DB2777',
            experience: 7,
            certifications: ['Soft Skills Trainer'],
            rate: '₹2,500/session',
            costPerSession: '₹2,500',
            skillTags: ['Communication', 'Leadership', 'Personality Development'],
            description: 'Soft Skills trainer with expertise in communication and personality development.',
            availability: {
                monday: true,
                tuesday: true,
                wednesday: false,
                thursday: true,
                friday: true,
                saturday: false,
                sunday: false,
            },
        },
        {
            id: '5',
            name: 'Senthil Nathan',
            initials: 'SN',
            subjects: ['Embedded C', 'IoT'],
            type: 'Visiting',
            utilization: 70,
            rating: 4.2,
            branch: 'Coimbatore',
            phone: '+91 97896 44510',
            email: 'senthil@upskill365.in',
            avatarColor: '#7C3AED',
            experience: 10,
            certifications: ['IoT Expert'],
            rate: '₹2,200/session',
            costPerSession: '₹2,200',
            skillTags: ['Embedded C', 'IoT', 'ARM'],
            description: 'IoT expert with 10+ years of experience in embedded systems and IoT.',
            availability: {
                monday: true,
                tuesday: true,
                wednesday: true,
                thursday: true,
                friday: true,
                saturday: true,
                sunday: false,
            },
        },
        {
            id: '6',
            name: 'Revathi K',
            initials: 'RK',
            subjects: ['Java', 'SQL'],
            type: 'In-house',
            utilization: 74,
            rating: 4.3,
            branch: 'Chennai',
            phone: '+91 93615 09742',
            email: 'revathi@upskill365.in',
            avatarColor: '#0F766E',
            experience: 4,
            certifications: ['Java Certified'],
            rate: '₹1,050/hr',
            staffCode: 'ST-004',
            department: 'Training',
            role: 'Trainer',
            specialization: 'Java Full Stack',
            status: 'Active',
            joinDate: '2022-06-15',
            gender: 'Female',
            dateOfBirth: '1994-03-12',
            maritalStatus: 'Single',
            address: '56, T.Nagar, Chennai - 600017',
            contactPerson: 'Kumar R',
            contactPersonMobileNumber: '9361509743',
            alternateMobileNumber: '9361509741',
            qualifications: [
                {
                    qualificationType: 'Degree',
                    degreeName: 'B.E. Computer Science',
                    major: 'Java Programming',
                    university: 'Anna University',
                },
            ],
            basicSalary: '₹30,000',
            perHourCost: '₹1,050',
            username: 'revathi.k',
            password: 'Password@123',
            description: 'Java trainer with expertise in Spring Boot and SQL.',
            availability: {
                monday: true,
                tuesday: true,
                wednesday: true,
                thursday: true,
                friday: true,
                saturday: false,
                sunday: false,
            },
        },
    ]);

    const getTypeColor = (type: string) => {
        return type === 'In-house' ? 'bg-blue-50 text-blue-700 border-blue-200' : 'bg-yellow-50 text-yellow-700 border-yellow-200';
    };

    const getUtilizationColor = (utilization: number) => {
        if (utilization >= 80) return 'text-green-600';
        if (utilization >= 60) return 'text-yellow-600';
        return 'text-red-600';
    };

    const getUtilizationBarColor = (utilization: number) => {
        if (utilization >= 80) return 'bg-green-600';
        if (utilization >= 60) return 'bg-yellow-600';
        return 'bg-red-600';
    };

    const renderStars = (rating: number) => {
        const fullStars = Math.floor(rating);
        const hasHalfStar = rating % 1 >= 0.5;
        const emptyStars = 5 - fullStars - (hasHalfStar ? 1 : 0);

        return (
            <div className="flex items-center gap-0.5">
                {[...Array(fullStars)].map((_, i) => (
                    <Star key={`full-${i}`} className="w-3.5 h-3.5 fill-yellow-400 text-yellow-400" />
                ))}
                {hasHalfStar && <Star className="w-3.5 h-3.5 fill-yellow-400 text-yellow-400" />}
                {[...Array(emptyStars)].map((_, i) => (
                    <Star key={`empty-${i}`} className="w-3.5 h-3.5 text-gray-300" />
                ))}
                <span className="ml-1 text-xs font-medium text-gray-600">{rating.toFixed(1)}</span>
            </div>
        );
    };

    const handleViewTrainer = (trainerId: string) => {
        navigate(`/trainers/${trainerId}`);
        setShowDropdown(null);
    };

    const handleLeaveSubstitution = () => {
        setShowLeaveModal(true);
    };

    const handleLeaveConfirm = (data: any) => {
        console.log('Leave request submitted:', data);
        setShowLeaveModal(false);
        toast.success('Leave request submitted successfully!');
    };

    const handleDeleteClick = (trainer: Trainer) => {
        setTrainerToDelete(trainer);
        setShowDeleteModal(true);
        setShowDropdown(null);
    };

    const handleConfirmDelete = () => {
        if (!trainerToDelete) return;
        setIsDeleting(true);
        setTimeout(() => {
            setTrainers(trainers.filter((t) => t.id !== trainerToDelete.id));
            setShowDeleteModal(false);
            setTrainerToDelete(null);
            setIsDeleting(false);
            toast.success(`Trainer "${trainerToDelete.name}" deleted successfully!`);
        }, 1000);
    };

    // Handler for Exit Trainer from three-dot menu
    const handleExitTrainer = (trainer: Trainer) => {
        setTrainerToExit(trainer);
        setSelectedTrainerId(trainer.id);
        setShowExitModal(true);
        setShowDropdown(null);
    };

    // Handler for Exit Trainer button in header
    const handleExitTrainerButton = () => {
        if (trainers.length === 0) {
            toast.warning('No trainers available to exit');
            return;
        }
        setTrainerToExit(null);
        setSelectedTrainerId(null);
        setShowExitModal(true);
    };

    const handleSaveExit = (data: any) => {
        // Find the trainers by IDs from the form data
        const trainerIds = data.trainerIds || [];

        if (trainerIds.length === 0) {
            toast.error('No trainers selected for exit');
            return;
        }

        // Find all trainers to update
        const trainersToUpdate = trainers.filter((t) => trainerIds.includes(t.id));

        if (trainersToUpdate.length === 0) {
            toast.error('Selected trainer(s) not found');
            return;
        }

        // Update all selected trainers
        setTrainers(
            trainers.map((t) =>
                trainerIds.includes(t.id)
                    ? {
                          ...t,
                          isExited: true,
                          exitDate: data.exitDate || data.startingDate || data.lastAttendDate || new Date().toISOString().split('T')[0],
                          exitType: data.exitType,
                          status: 'Inactive',
                      }
                    : t,
            ),
        );

        // Show success message with trainer names
        const trainerNames = trainersToUpdate.map((t) => t.name).join(', ');
        toast.success(`Trainer${trainersToUpdate.length > 1 ? 's' : ''} "${trainerNames}" exited successfully!`);

        setShowExitModal(false);
        setTrainerToExit(null);
        setSelectedTrainerId(null);
    };

    const handleAddTrainer = (formData: TrainerFormData) => {
        // Generate avatar color
        const avatarColors = ['#4338CA', '#0D9488', '#D97706', '#DB2777', '#7C3AED', '#0F766E', '#B45309', '#BE185D'];
        const randomColor = avatarColors[Math.floor(Math.random() * avatarColors.length)];

        const newTrainer: Trainer = {
            id: String(trainers.length + 1),
            name: formData.name,
            initials: formData.name
                .split(' ')
                .map((n) => n[0])
                .join('')
                .substring(0, 2)
                .toUpperCase(),
            subjects: [], // Visiting trainers don't have subjects
            type: 'Visiting', // Always Visiting
            utilization: 0,
            rating: 0,
            branch: formData.branch,
            phone: formData.phone,
            email: formData.email,
            avatarColor: randomColor,
            experience: 0,
            certifications: [],
            rate: formData.rate || formData.costPerSession || '',
            availability: formData.availability || {
                monday: true,
                tuesday: true,
                wednesday: true,
                thursday: true,
                friday: true,
                saturday: false,
                sunday: false,
            },
            profileImage: formData.profileImage || null,
            description: formData.description || '',
            costPerSession: formData.costPerSession || '',
            skillTags: formData.skillTags || [],
            documents: formData.documents || [],
            isExited: false,
            status: 'Active',
        };

        setTrainers([...trainers, newTrainer]);
        setShowAddModal(false);
        toast.success('Trainer added successfully!');
    };

    const handleEditTrainer = (formData: TrainerFormData) => {
        if (!editingTrainer) return;

        const updatedTrainer: Trainer = {
            ...editingTrainer,
            name: formData.name,
            email: formData.email,
            phone: formData.phone,
            branch: formData.branch,
            rate: formData.rate || formData.costPerSession || '',
            availability: formData.availability || {
                monday: true,
                tuesday: true,
                wednesday: true,
                thursday: true,
                friday: true,
                saturday: false,
                sunday: false,
            },
            profileImage: formData.profileImage || null,
            description: formData.description || '',
            costPerSession: formData.costPerSession || '',
            skillTags: formData.skillTags || [],
            documents: formData.documents || [],
        };

        setTrainers(trainers.map((t) => (t.id === editingTrainer.id ? updatedTrainer : t)));
        setEditingTrainer(null);
        setShowAddModal(false);
        toast.success('Trainer updated successfully!');
    };

    // Handler for opening analysis modal
    const handleAnalysisClick = () => {
        setShowAnalysisModal(true);
    };

    // Filter trainers
    const filteredTrainers = trainers.filter((trainer) => {
        const matchesSearch =
            trainer.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
            trainer.subjects.some((s) => s.toLowerCase().includes(searchTerm.toLowerCase())) ||
            trainer.branch.toLowerCase().includes(searchTerm.toLowerCase()) ||
            (trainer.staffCode && trainer.staffCode.toLowerCase().includes(searchTerm.toLowerCase()));
        const matchesType = filterType === 'All' || trainer.type === filterType;
        return matchesSearch && matchesType;
    });

    // Pagination
    const totalPages = Math.ceil(filteredTrainers.length / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const currentTrainers = filteredTrainers.slice(startIndex, startIndex + itemsPerPage);

    // Define columns for Trainers table with S.No
    const columns: Column<Trainer>[] = [
        {
            key: 'sno',
            header: 'S.No',
            align: 'center',
            accessor: (_row: Trainer, index: number) => {
                const page = currentPage || 1;
                const entries = itemsPerPage;
                const calculatedIndex = (page - 1) * entries + (index || 0) + 1;
                return <span className="text-sm text-gray-600">{calculatedIndex}</span>;
            },
        },
        {
            key: 'trainer',
            header: 'TRAINER',
            accessor: (row) => (
                <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full flex items-center justify-center text-white text-xs font-bold flex-shrink-0" style={{ backgroundColor: row.avatarColor }}>
                        {row.initials}
                    </div>
                    <div>
                        <div className="text-sm font-medium text-gray-900">{row.name}</div>
                        <div className="text-xs text-gray-500">{row.branch}</div>
                        {row.specialization && <div className="text-xs text-gray-400">{row.specialization}</div>}
                        {row.isExited && (
                            <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-medium bg-red-50 text-red-600 border border-red-200">
                                <LogOut className="w-3 h-3" />
                                Exited
                            </span>
                        )}
                    </div>
                </div>
            ),
        },
        {
            key: 'subjects',
            header: 'SUBJECTS',
            accessor: (row) => (
                <div className="flex flex-wrap gap-1">
                    {row.subjects.map((subject, idx) => (
                        <span key={idx} className="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-gray-100 text-gray-700">
                            {subject}
                        </span>
                    ))}
                </div>
            ),
        },
        {
            key: 'type',
            header: 'TYPE',
            accessor: (row) => <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium border ${getTypeColor(row.type)}`}>{row.type}</span>,
        },
        {
            key: 'utilization',
            header: 'UTILIZATION',
            accessor: (row) => (
                <div className="flex items-center gap-2 min-w-[120px]">
                    <div className="flex-1 h-2 bg-gray-200 rounded-full overflow-hidden">
                        <div className={`h-full rounded-full ${getUtilizationBarColor(row.utilization)}`} style={{ width: `${row.utilization}%` }}></div>
                    </div>
                    <span className={`text-xs font-medium ${getUtilizationColor(row.utilization)}`}>{row.utilization}%</span>
                </div>
            ),
        },
        {
            key: 'rating',
            header: 'RATING',
            accessor: (row) => renderStars(row.rating),
        },
        {
            key: 'branch',
            header: 'BRANCH',
            accessor: (row) => (
                <div className="flex items-center gap-1.5">
                    <MapPin className="w-3.5 h-3.5 text-gray-400" />
                    <span className="text-sm text-gray-700">{row.branch}</span>
                </div>
            ),
        },
        {
            key: 'actions',
            header: 'ACTION',
            align: 'center',
            accessor: (row) => {
                const [dropdownOpen, setDropdownOpen] = useState<string | null>(null);
                return (
                    <div className="flex items-center justify-center gap-1 relative">
                        <ActionButtons
                            onView={() => handleViewTrainer(row.id)}
                            onEdit={() => {
                                setEditingTrainer(row);
                                setShowAddModal(true);
                            }}
                            onDelete={() => handleDeleteClick(row)}
                            viewTooltip="View Trainer"
                            editTooltip="Edit Trainer"
                            deleteTooltip="Delete Trainer"
                            size="sm"
                        />
                        {/* 3-Dot Menu */}
                        <div className="relative">
                            <button
                                onClick={(e) => {
                                    e.stopPropagation();
                                    setDropdownOpen(dropdownOpen === row.id ? null : row.id);
                                }}
                                className="p-1.5 text-gray-400 hover:text-gray-700 transition-colors rounded hover:bg-gray-100"
                                title="More Actions"
                            >
                                <MoreVertical className="w-4 h-4" />
                            </button>
                            {dropdownOpen === row.id && (
                                <>
                                    <div className="fixed inset-0 z-40" onClick={() => setDropdownOpen(null)} />
                                    <div className="absolute right-0 mt-1 z-50 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-1">
                                        <button onClick={() => handleExitTrainer(row)} className="w-full px-4 py-2 text-left text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2">
                                            <LogOut className="w-4 h-4" />
                                            Exit Trainer
                                        </button>
                                    </div>
                                </>
                            )}
                        </div>
                    </div>
                );
            },
        },
    ];

    // Stats calculation
    const totalTrainers = trainers.length;
    const inHouseCount = trainers.filter((t) => t.type === 'In-house').length;
    const visitingCount = trainers.filter((t) => t.type === 'Visiting').length;
    const avgRating = trainers.reduce((acc, t) => acc + t.rating, 0) / trainers.length;

    return (
        <>
            <ToastContainer toasts={toast.toasts} onRemove={toast.removeToast} />

            <div className="p-6">
                {/* Page Header */}
                <div className="mb-6">
                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                        <div>
                            <h1 className="text-2xl font-bold text-primary">Trainers</h1>
                            <p className="text-gray-500 text-sm mt-1">Manage all trainers and their availability</p>
                        </div>
                        <div className="flex items-center gap-3">
                            <ButtonUI variant="outline" size="md" icon={<BarChart3 className="w-4 h-4" />} onClick={handleAnalysisClick}>
                                Trainer Analysis
                            </ButtonUI>
                            <ButtonUI variant="secondary" size="md" icon={<Plus className="w-4 h-4" />} onClick={() => setShowAddModal(true)}>
                                Add Trainer
                            </ButtonUI>
                            <ButtonUI
                                variant="outline"
                                size="md"
                                icon={<LogOut className="w-4 h-4" />}
                                onClick={handleExitTrainerButton}
                                className="border-red-300 text-red-600 hover:bg-red-50 hover:border-red-400"
                            >
                                Exit Trainer
                            </ButtonUI>
                        </div>
                    </div>
                </div>

                {/* Stats Cards */}
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
                    <div className="bg-white rounded-lg border border-gray-200 p-4">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm text-gray-500">Total Trainers</p>
                                <p className="text-2xl font-bold text-primary">{totalTrainers}</p>
                            </div>
                            <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                                <Users className="w-5 h-5 text-primary" />
                            </div>
                        </div>
                    </div>
                    <div className="bg-white rounded-lg border border-gray-200 p-4">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm text-gray-500">In-house</p>
                                <p className="text-2xl font-bold text-blue-600">{inHouseCount}</p>
                            </div>
                            <div className="w-10 h-10 rounded-full bg-blue-50 flex items-center justify-center">
                                <UserCheck className="w-5 h-5 text-blue-600" />
                            </div>
                        </div>
                    </div>
                    <div className="bg-white rounded-lg border border-gray-200 p-4">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm text-gray-500">Visiting</p>
                                <p className="text-2xl font-bold text-yellow-600">{visitingCount}</p>
                            </div>
                            <div className="w-10 h-10 rounded-full bg-yellow-50 flex items-center justify-center">
                                <UserX className="w-5 h-5 text-yellow-600" />
                            </div>
                        </div>
                    </div>
                    <div className="bg-white rounded-lg border border-gray-200 p-4">
                        <div className="flex items-center justify-between">
                            <div>
                                <p className="text-sm text-gray-500">Avg Rating</p>
                                <p className="text-2xl font-bold text-primary">{avgRating.toFixed(1)}</p>
                            </div>
                            <div className="w-10 h-10 rounded-full bg-yellow-50 flex items-center justify-center">
                                <Star className="w-5 h-5 text-yellow-400" />
                            </div>
                        </div>
                    </div>
                </div>

                {/* Filters */}
                <div className="flex flex-wrap items-center gap-4 mb-6 bg-white p-4 rounded-lg border border-gray-200">
                    <div className="flex-1 min-w-[200px] relative">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                        <input
                            type="text"
                            placeholder="Search trainer name, subject, branch..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            className="w-full pl-9 pr-4 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:border-secondary focus:ring-2 focus:ring-secondary/20"
                        />
                    </div>

                    <div className="flex items-center gap-2">
                        <span className="text-sm text-gray-500">Type:</span>
                        <div className="flex gap-1 bg-gray-100 p-1 rounded-lg">
                            {['All', 'In-house', 'Visiting'].map((type) => (
                                <button
                                    key={type}
                                    onClick={() => setFilterType(type as any)}
                                    className={`
                                        px-3 py-1 rounded-md text-sm font-medium transition-all whitespace-nowrap
                                        ${filterType === type ? 'bg-white text-secondary shadow-sm' : 'text-gray-600 hover:text-gray-800'}
                                    `}
                                >
                                    {type}
                                </button>
                            ))}
                        </div>
                    </div>

                    <div className="ml-auto text-sm text-gray-500">
                        Showing {currentTrainers.length} of {filteredTrainers.length} trainers
                    </div>
                </div>

                {/* Table */}
                <Table data={currentTrainers} columns={columns} emptyMessage="No trainers found" />

                {/* Pagination */}
                {filteredTrainers.length > 0 && (
                    <Pagination
                        currentPage={currentPage}
                        totalPages={totalPages}
                        totalItems={filteredTrainers.length}
                        startIndex={startIndex}
                        itemsPerPage={itemsPerPage}
                        onPageChange={setCurrentPage}
                    />
                )}

                {/* Add/Edit Trainer Modal */}
                <AddTrainerModal
                    isOpen={showAddModal}
                    onClose={() => {
                        setShowAddModal(false);
                        setEditingTrainer(null);
                    }}
                    onSave={editingTrainer ? handleEditTrainer : handleAddTrainer}
                    editingTrainer={editingTrainer}
                />

                {/* Leave & Substitution Modal */}
                <LeaveSubstitutionModal isOpen={showLeaveModal} onClose={() => setShowLeaveModal(false)} onConfirm={handleLeaveConfirm} />

                {/* Exit Trainer Modal */}
                <ExitTrainerModal
                    isOpen={showExitModal}
                    onClose={() => {
                        setShowExitModal(false);
                        setTrainerToExit(null);
                        setSelectedTrainerId(null);
                    }}
                    onSave={handleSaveExit}
                    trainers={trainers.map((t) => ({
                        id: t.id,
                        name: t.name,
                        code: t.staffCode || '',
                        branch: t.branch,
                    }))}
                    selectedTrainerId={selectedTrainerId}
                />

                {/* Trainer Analysis Modal */}
                <TrainerAnalysisModal isOpen={showAnalysisModal} onClose={() => setShowAnalysisModal(false)} />

                {/* Delete Confirmation Modal */}
                <ConfirmationModal
                    isOpen={showDeleteModal}
                    onClose={() => {
                        setShowDeleteModal(false);
                        setTrainerToDelete(null);
                    }}
                    onConfirm={handleConfirmDelete}
                    title="Delete Trainer"
                    message={`Are you sure you want to delete "${trainerToDelete?.name}"? This action cannot be undone and will remove all associated data.`}
                    type="danger"
                    confirmText="Delete"
                    cancelText="Cancel"
                    isLoading={isDeleting}
                />
            </div>
        </>
    );
};

export default Trainers;
