import { useFormik } from "formik";
import * as Yup from "yup";
import Modal from "../../components/Modals";
import Select from "../../components/Select";
import Avatar from "../../components/Avatar";
import user from "../../assets/images/auth/user.png";
import { useEffect, useState } from "react";
import api from '../../api/axios';
import { toast } from 'react-toastify';
import config from '../../config';

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (data: any) => void;
    staffName?: string;
    date?: Date;
    staffId?: number;
}

const SwapStaff = ({ open, onClose, onSave, staffName, date, staffId }: Props) => {
    const [loading, setLoading] = useState(false);
    const [batches, setBatches] = useState<any[]>([]);
    const [staffOptions, setStaffOptions] = useState<any[]>([]);
    const [absentStaff, setAbsentStaff] = useState<any>(null);
    const [assignments, setAssignments] = useState<any[]>([]);

    const getImageUrl = (imagePath: string | null): string => {
        if (!imagePath) return user;
        if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
            return imagePath;
        }
        return `${config.storageUrl}/${imagePath}`;
    };

    const formatTimeDisplay = (time: string): string => {
        if (!time || time === '--:--') return '--:--';
        try {
            let timeStr = time.trim();
            if (timeStr.split(':').length >= 3) {
                timeStr = timeStr.substring(0, 5);
            }
            const parts = timeStr.split(':');
            if (parts.length < 2) return timeStr;
            const hours = parseInt(parts[0], 10);
            const minutes = parts[1];
            if (isNaN(hours) || isNaN(parseInt(minutes))) return timeStr;
            const ampm = hours >= 12 ? 'PM' : 'AM';
            const displayHour = hours % 12 || 12;
            const displayHourStr = displayHour.toString().padStart(2, '0');
            return `${displayHourStr}:${minutes} ${ampm}`;
        } catch (error) {
            return time;
        }
    };

    useEffect(() => {
        const fetchData = async () => {
            if (!open || !staffId) return;

            setLoading(true);
            try {
                const response = await api.get('/staff-attendance/batches', {
                    params: {
                        staff_id: staffId,
                        date: date?.toISOString().split('T')[0]
                    }
                });

                if (response.data.status) {
                    const batchesData = response.data.data.batches || [];
                    const staffData = response.data.data.available_staff || [];

                    setBatches(batchesData);
                    setStaffOptions(staffData);
                    setAbsentStaff(response.data.data.absent_staff || null);

                    // Initialize assignments
                    const initialAssignments = batchesData.map((batch: any) => ({
                        schedule_id: batch.schedule_id,
                        batch_name: batch.batch_name,
                        time_display: `${batch.start_time_formatted || formatTimeDisplay(batch.start_time)} - ${batch.end_time_formatted || formatTimeDisplay(batch.end_time)}`,
                        new_staff_id: "",
                    }));
                    setAssignments(initialAssignments);
                }
            } catch (error: any) {
                console.error('Failed to fetch data:', error);
                toast.error(error.response?.data?.message || 'Failed to load batch data');
            } finally {
                setLoading(false);
            }
        };

        fetchData();
    }, [open, date, staffId]);

    const handleStaffChange = (index: number, selectedOption: any) => {
        console.log('Selected option:', selectedOption);

        const updated = [...assignments];
        // Handle both cases: option object with value, or direct value
        if (selectedOption && typeof selectedOption === 'object' && 'value' in selectedOption) {
            updated[index].new_staff_id = String(selectedOption.value);
        } else if (selectedOption && typeof selectedOption === 'object' && selectedOption.value) {
            updated[index].new_staff_id = String(selectedOption.value);
        } else {
            updated[index].new_staff_id = String(selectedOption || "");
        }
        setAssignments(updated);
    };

    // Find selected option for a given staff_id
    const getSelectedOption = (staffId: string) => {
        if (!staffId) return null;
        return staffOptions.find(opt => String(opt.value) === String(staffId)) || null;
    };

    const handleSubmit = async () => {
        const unassigned = assignments.filter(a => !a.new_staff_id || a.new_staff_id === "");
        if (unassigned.length > 0) {
            toast.warning(`Please assign replacement staff for all ${batches.length} batch(es)`);
            return;
        }

        setLoading(true);
        try {
            const response = await api.post('/staff-attendance/reschedule', {
                staff_id: staffId,
                date: date?.toISOString().split('T')[0],
                batch_assignments: assignments.map(a => ({
                    schedule_id: a.schedule_id,
                    new_staff_id: a.new_staff_id,
                })),
            });

            if (response.data.status) {
                toast.success(response.data.message || 'Staff rescheduled successfully');
                onSave(response.data.data);
                onClose();
            }
        } catch (error: any) {
            console.error('Failed to reschedule:', error);
            toast.error(error.response?.data?.message || 'Failed to reschedule');
        } finally {
            setLoading(false);
        }
    };

    const allAssigned = assignments.every(a => a.new_staff_id && a.new_staff_id !== "");

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Swap Staff - Reschedule"
            maxWidth="max-w-2xl"
            footer={
                <>
                    <button onClick={onClose} className="btn btn-outline-danger" type="button" disabled={loading}>
                        Cancel
                    </button>
                    <button
                        onClick={handleSubmit}
                        className="btn btn-primary"
                        type="button"
                        disabled={loading || batches.length === 0}
                    >
                        {loading ? 'Saving...' : 'Confirm Reschedule'}
                    </button>
                </>
            }
        >
            {loading ? (
                <div className="flex justify-center items-center py-12">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                    <span className="ml-3">Loading batches...</span>
                </div>
            ) : (
                <div className="grid grid-cols-12 gap-5">
                    {/* Absent Staff Header */}
                    <div className="col-span-12 flex items-center justify-between">
                        <div className="flex items-center gap-2">
                            <Avatar
                                src={absentStaff?.avatar ? getImageUrl(absentStaff.avatar) : user}
                                size="md"
                            />
                            <div>
                                <div className="text-sm font-semibold">
                                    {absentStaff?.name || staffName || 'Staff'}
                                </div>
                                <div className="text-xs text-gray-500">
                                    {absentStaff?.role || 'Staff'}
                                </div>
                            </div>
                        </div>
                        <span className="bg-red-50 text-red-500 px-3 py-1 rounded-full text-sm font-medium">
                            Absent
                        </span>
                    </div>

                    <div className="col-span-12">
                        <hr className="border-gray-200" />
                    </div>

                    <div className="col-span-12 flex items-center justify-between">
                        <label className="text-black font-medium">Today's Batches</label>
                        <span className="bg-primary text-white rounded-full px-3 py-1 text-sm font-medium">
                            {batches.length}
                        </span>
                    </div>

                    <div className="col-span-12 pe-3" style={{ maxHeight: "400px", overflowY: "auto" }}>
                        {batches.length === 0 ? (
                            <div className="text-center py-8 text-gray-400">
                                No batches found for this date
                            </div>
                        ) : (
                            assignments.map((assignment, index) => {
                                const selectedOption = getSelectedOption(assignment.new_staff_id);

                                return (
                                    <div className="mb-3" key={index}>
                                        <div className={`p-3 rounded-xl border flex items-center justify-between ${
                                            assignment.new_staff_id ? 'bg-green-50 border-green-300' : 'bg-gray-50'
                                        }`}>
                                            <div className="flex flex-col">
                                                <label className="font-medium text-sm">
                                                    {assignment.batch_name}
                                                </label>
                                                <label className="text-xs bg-red-50 text-red-500 px-2 py-1 rounded mt-1 inline-block whitespace-nowrap">
                                                    {assignment.time_display}
                                                </label>
                                            </div>

                                            <div className="flex flex-col gap-1 w-64">
                                                {/* ✅ Custom Select Component */}
                                                <Select
                                                    placeholder="Select Staff"
                                                    options={staffOptions}
                                                    value={selectedOption}
                                                    onChange={(val: any) => handleStaffChange(index, val)}
                                                />

                                                {!assignment.new_staff_id && (
                                                    <span className="text-xs text-red-500">
                                                        * Required
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                    </div>
                                );
                            })
                        )}
                    </div>


                </div>
            )}
        </Modal>
    );
};

export default SwapStaff;
