import { useEffect, useState } from "react";
import IconArchive from "../../components/Icon/IconArchive";
import AddExpense from "../../modals/manage_expense/AddExpense";
import api from '../../api/axios';
import { toast } from 'react-toastify';

interface Props {
    open: boolean;
    title?: string;
    message?: string;
    onClose: () => void;
    onConfirm: () => void;
    studentName?: string;
    studentId?: number; // Add student ID prop
}

const DropModal = ({
    open,
    title = "Drop Confirmation",
    message = "Are you sure you want to drop this student?",
    onClose,
    onConfirm,
    studentName,
    studentId,
}: Props) => {
    const [show, setShow] = useState(open);
    const [showExpense, setShowExpense] = useState(false);
    const [isProcessing, setIsProcessing] = useState(false);

    useEffect(() => {
        setShow(open);
    }, [open]);

    const handleDropConfirm = () => {
        setShow(false); // Hide drop confirmation modal
        setShowExpense(true); // Show AddExpense modal
    };

    const handleAddSave = async (data: any) => {
        setIsProcessing(true);
        try {
            // Step 1: Call the expense API
            const expenseResponse = await api.post('/expenses/add', {
                expense_name: data.expense_name,
                category: data.category,
                amount: data.amount,
                date: data.start_date,
                description: data.description,
                student_name: studentName
            });

            if (!expenseResponse.data.status) {
                throw new Error(expenseResponse.data?.message || 'Failed to add expense');
            }

            toast.success('Expense added successfully');

            // Step 2: Call the status update API to drop the student
            if (studentId) {
                const statusResponse = await api.put(`/student/update-status/${studentId}`, {
                    status: 4, // drop student
                });

                if (!statusResponse.data.status) {
                    throw new Error(statusResponse.data?.message || 'Failed to update student status');
                }

                toast.success('Student dropped successfully');
            } else {
                console.warn('No student ID provided for status update');
            }

            // Step 3: Execute the parent's onConfirm callback
            onConfirm();

            // Step 4: Close modals
            setShowExpense(false);
            onClose();

        } catch (error: any) {
            const errorMessage = error.response?.data?.message || error.message || 'Failed to process drop';
            toast.error(errorMessage);
            // Re-throw to prevent AddExpense form reset
            throw error;
        } finally {
            setIsProcessing(false);
        }
    };

    const handleCancelExpense = () => {
        setShowExpense(false);
        // Show the confirmation modal again
        setShow(true);
    };

    if (!show && !showExpense) return null;

    return (
        <>
            {/* Drop Confirmation Modal */}
            {show && (
                <div className="fixed inset-0 bg-black/60 z-[99999] flex items-center justify-center px-4">
                    <div className="panel border-0 p-0 rounded-lg overflow-hidden w-full max-w-md bg-white">
                        <div className="flex py-4 bg-[#fbfbfb] items-center justify-center">
                            <div className="w-14 h-14 rounded-full bg-orange-100 flex items-center justify-center">
                                <IconArchive className="text-warning w-7 h-7" />
                            </div>
                        </div>

                        <div className="p-5 text-center">
                            <h2 className="text-lg font-semibold text-black">
                                {title}
                            </h2>
                            <p className="text-sm text-gray-500 mt-2">
                                {message}
                            </p>

                            <div className="flex justify-center gap-4 mt-6">
                                <button
                                    type="button"
                                    className="btn btn-outline-secondary"
                                    onClick={onClose}
                                    disabled={isProcessing}
                                >
                                    Cancel
                                </button>
                                <button
                                    type="button"
                                    className="btn btn-warning flex items-center gap-2"
                                    onClick={handleDropConfirm}
                                    disabled={isProcessing}
                                >
                                    {isProcessing && (
                                        <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24">
                                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                                        </svg>
                                    )}
                                    Yes, Drop
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* AddExpense Modal - without isProcessing prop */}
            {showExpense && (
                <AddExpense
                    open={showExpense}
                    studentName={studentName}
                    onClose={handleCancelExpense}
                    onSave={handleAddSave}
                />
            )}
        </>
    );
};

export default DropModal;
