import IconCalendar from '../../components/Icon/IconCalendar';
import { Link, useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { useEffect, useState, useCallback } from 'react';
import { setPageTitle } from '../../store/themeConfigSlice';
import user from '../../assets/images/auth/user.png';
import Avatar from '../../components/Avatar';
import user1 from '../../assets/images/auth/user_7.png';
import Select from '../../components/Select';
import MonthPicker from '../../components/MonthPicker';
import IconChevronLeft from '../../components/Icon/IconChevronLeft';
import IconChevronRight from '../../components/Icon/IconChevronRight';
import api from '../../api/axios';
import { toast } from 'react-toastify';
import config from '../../config';
type AttendanceStatus = "present" | "absent";

type Student = {
    id: string;
    student_name: string;
    std_id: string;
    image: string;
    course: string;
    attendance: Record<string, AttendanceStatus>;
};

interface PaginationData {
    current_page: number;
    last_page: number;
    per_page: number;
    total: number;
    next_page_url: string | null;
    prev_page_url: string | null;
}

const StudentAttendance = () => {
    const dispatch = useDispatch();
    const navigate = useNavigate();

    useEffect(() => {
        dispatch(setPageTitle('Student Attendance'));
    }, [dispatch]);

    // State variables
    const [students, setStudents] = useState<Student[]>([]);
    const [batches, setBatches] = useState<{ value: string; label: string }[]>([]);
    const [selectedBatch, setSelectedBatch] = useState<string>("");
    const [selectedMonth, setSelectedMonth] = useState<Date>(new Date());
    const [loading, setLoading] = useState(true);
    const [search, setSearch] = useState("");
    const [perPage, setPerPage] = useState(25);
    const [pagination, setPagination] = useState<PaginationData>({
        current_page: 1,
        last_page: 1,
        per_page: 25,
        total: 0,
        next_page_url: null,
        prev_page_url: null
    });
    const [searchTimeout, setSearchTimeout] = useState<NodeJS.Timeout | null>(null);
    const [summary, setSummary] = useState({
        total_present: 0,
        total_absent: 0,
        total_students: 0
    });
    const [days, setDays] = useState<{ day: number; date: string; is_weekend: boolean; day_name: string }[]>([]);

    // Fetch attendance data
    const fetchAttendance = useCallback(async () => {
        setLoading(true);
        try {
            const params: any = {
                page: pagination.current_page,
                per_page: perPage,
            };

            if (search) {
                params.search = search;
            }
            if (selectedBatch) {
                params.batch_id = selectedBatch;
            }
            if (selectedMonth) {
                params.month = `${selectedMonth.getFullYear()}-${String(selectedMonth.getMonth() + 1).padStart(2, '0')}`;
            }

            const response = await api.get('/training/attendance/list', { params });

            if (response.data.status === 200) {
                setStudents(response.data.data.items || []);
                setPagination({
                    current_page: response.data.data.current_page,
                    last_page: response.data.data.last_page,
                    per_page: response.data.data.per_page,
                    total: response.data.data.total,
                    next_page_url: response.data.data.next_page_url,
                    prev_page_url: response.data.data.prev_page_url
                });

                setSummary(response.data.data.summary || {
                    total_present: 0,
                    total_absent: 0,
                    total_students: 0
                });

                setDays(response.data.data.days_in_month || []);

                // Set batches for filter
                if (response.data.data.batches) {
                    const batchOptions = response.data.data.batches.map((batch: any) => ({
                        value: batch.id.toString(),
                        label: batch.batch_name
                    }));
                    setBatches(batchOptions);
                }
            }
        } catch (error) {
            console.error("Error fetching attendance:", error);
            toast.error("Failed to fetch attendance data");
        } finally {
            setLoading(false);
        }
    }, [pagination.current_page, perPage, search, selectedBatch, selectedMonth]);

    useEffect(() => {
        fetchAttendance();
    }, [fetchAttendance]);

    // Handle search with debounce
    const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
        const value = e.target.value;
        setSearch(value);
        setPagination(prev => ({ ...prev, current_page: 1 }));

        if (searchTimeout) {
            clearTimeout(searchTimeout);
        }

        const timeout = setTimeout(() => {}, 500);
        setSearchTimeout(timeout);
    };

    // Handle page change
    const handlePageChange = (page: number) => {
        setPagination(prev => ({ ...prev, current_page: page }));
    };

    // Handle per page change
    const handlePerPageChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
        const newPerPage = Number(e.target.value);
        setPerPage(newPerPage);
        setPagination(prev => ({ ...prev, current_page: 1, per_page: newPerPage }));
    };

    // Handle batch change
    const handleBatchChange = (val: any) => {
        setSelectedBatch(val?.value || "");
        setPagination(prev => ({ ...prev, current_page: 1 }));
    };

    // Handle month change
    const handleMonthChange = (date: Date | null) => {
        if (date) {
            setSelectedMonth(date);
            setPagination(prev => ({ ...prev, current_page: 1 }));
        }
    };

    // Update attendance status
    const updateAttendance = async (studentId: string, date: string, status: AttendanceStatus) => {
        try {
            await api.post('/training/attendance/update', {
                student_id: studentId,
                date: date,
                attendance: status
            });

            // Update local state
            setStudents(prevStudents =>
                prevStudents.map(student => {
                    if (student.id === studentId) {
                        return {
                            ...student,
                            attendance: {
                                ...student.attendance,
                                [date]: status
                            }
                        };
                    }
                    return student;
                })
            );

            toast.success("Attendance updated successfully");
        } catch (error) {
            console.error("Error updating attendance:", error);
            toast.error("Failed to update attendance");
        }
    };


    // Check if a date is in the past or today
    const isPastDate = (dateStr: string) => {
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        // Parse the date string in local timezone to avoid UTC issues
        const [year, month, day] = dateStr.split('-').map(Number);
        const checkDate = new Date(year, month - 1, day);
        checkDate.setHours(0, 0, 0, 0);

        return checkDate <= today;
    };

    // Table skeleton loader
    const TableSkeleton = () => (
        <tr className="animate-pulse">
            <td className="p-3">
                <div className="flex items-center gap-2">
                    <div className="w-8 h-8 bg-gray-200 rounded-full"></div>
                    <div>
                        <div className="h-4 w-28 bg-gray-200 rounded mb-1"></div>
                        <div className="h-3 w-20 bg-gray-200 rounded"></div>
                    </div>
                </div>
            </td>
            {days.slice(0, 5).map((_, idx) => (
                <td key={idx} className="p-2 text-center">
                    <div className="w-7 h-7 bg-gray-200 rounded-full mx-auto"></div>
                </td>
            ))}
        </tr>
    );

    // Format month display
    const formatMonth = (date: Date) => {
        return date.toLocaleString('default', { month: 'long', year: 'numeric' });
    };

    // At the top of your file or from a config
    const storageBaseUrl = config.storageUrl; // e.g., "http://192.168.3.100:8009/storage/"


    // Helper function to get the full image URL
    const getImageUrl = (imagePath: string | null): string => {
        if (!imagePath) return user; // Return default user image

        // If it's already a full URL (http/https), return as is
        if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
            return imagePath;
        }

        // If it's a relative path, prepend storage URL
        return `${storageBaseUrl}/${imagePath}`;
    };
    return (
        <>
            <div className="flex items-center justify-between gap-2 mb-2 flex-wrap">
                <ul className="flex space-x-2 items-center">
                    <li>
                        <Link to="/manage_attendance" className="text-primary text-lg hover:underline">
                            Student Attendance
                        </Link>
                    </li>
                    <li className="before:content-['/'] ml-2">
                        <span>Manage Training</span>
                    </li>
                </ul>
            </div>

            {/* Summary Cards */}
            {/* <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                <div className="bg-white rounded-xl shadow-md p-4 border-l-4 border-blue-500">
                    <div className="text-sm text-gray-500">Total Students</div>
                    <div className="text-2xl font-bold">{summary.total_students}</div>
                </div>
                <div className="bg-white rounded-xl shadow-md p-4 border-l-4 border-green-500">
                    <div className="text-sm text-gray-500">Present Today</div>
                    <div className="text-2xl font-bold text-green-600">{summary.total_present}</div>
                </div>
                <div className="bg-white rounded-xl shadow-md p-4 border-l-4 border-red-500">
                    <div className="text-sm text-gray-500">Absent Today</div>
                    <div className="text-2xl font-bold text-red-600">{summary.total_absent}</div>
                </div>
            </div> */}

            <div className="pt-4">
                <div className="p-4 rounded-xl shadow-md bg-white w-full max-w-full overflow-hidden">
                    {/* Filters */}
                    <div className="flex items-end justify-between gap-4 mb-4 flex-wrap">
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 w-full">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    Batch
                                </label>
                                <Select
                                    options={batches}
                                    placeholder="All Batches"
                                    value={batches.find(b => b.value === selectedBatch)}
                                    onChange={handleBatchChange}
                                    isClearable
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    Select Month
                                </label>
                                <MonthPicker
                                    value={selectedMonth}
                                    onChange={handleMonthChange}
                                />
                            </div>
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    Search Student
                                </label>
                                <div className="relative">
                                    <input
                                        type="text"
                                        placeholder="Search by name or ID..."
                                        value={search}
                                        onChange={handleSearch}
                                        className="px-4 py-2 pl-10 border rounded-md w-full focus:outline-none focus:ring-2 focus:ring-primary"
                                    />
                                    <svg className="absolute left-3 top-2.5 w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                                    </svg>
                                </div>
                            </div>
                        </div>
                    </div>

                    {/* Attendance Table */}
                    <div className="overflow-x-auto">
                        <table className="min-w-max border text-xs">
                            <thead>
                                <tr className="bg-gray-100">
                                    <th className="p-3 text-left min-w-[200px] sticky left-0 bg-white z-20">
                                        Student
                                    </th>
                                    {days.map((day) => (
                                        <th
                                            key={day.day}
                                            className={`p-2 text-center min-w-[80px]
                                            ${day.is_weekend ? "bg-gray-100 text-gray-400" : ""}`}
                                        >
                                            <div className="flex flex-col">
                                                <span>{`${String(day.day).padStart(2, '0')}/${String(selectedMonth.getMonth() + 1).padStart(2, '0')}`}</span>
                                                <span className="text-xs text-gray-400">{day.day_name}</span>
                                            </div>
                                        </th>
                                    ))}
                                </tr>
                            </thead>
                            <tbody>
                                {loading ? (
                                    <>
                                        <TableSkeleton />
                                        <TableSkeleton />
                                        <TableSkeleton />
                                        <TableSkeleton />
                                        <TableSkeleton />
                                        <TableSkeleton />
                                    </>
                                ) : students.length === 0 ? (
                                    <tr>
                                        <td colSpan={days.length + 1} className="text-center py-8 text-gray-500">
                                            No students found
                                        </td>
                                    </tr>
                                ) : (
                                    students.map((student) => (
                                        <tr key={student.id} className="border-t hover:bg-gray-50">
                                            <td className="p-3 sticky left-0 bg-white z-10">
                                                <div className="flex items-center gap-2">
                                                    <Avatar src={getImageUrl(student.image) || user} size="sm" />
                                                    <div>
                                                        <div className="font-semibold text-sm">
                                                            {student.student_name}
                                                        </div>
                                                        <div className="text-gray-400 text-xs">
                                                            {student.std_id}
                                                        </div>
                                                        <div className="text-gray-400 text-xs">
                                                            {student.course}
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                            {days.map((day) => {
                                                const status = student.attendance?.[day.date];
                                                const isPast = isPastDate(day.date);

                                                return (
                                                    <td key={day.day} className="text-center p-2">
                                                        {isPast ? (
                                                            status === "present" ? (
                                                                <span
                                                                    className="inline-flex items-center justify-center w-7 h-7 rounded-full bg-green-100 text-green-600 font-bold text-xs cursor-pointer hover:bg-green-200 transition-colors"
                                                                    // onClick={() => updateAttendance(student.id, day.date, "absent")}
                                                                >
                                                                    P
                                                                </span>
                                                            ) : status === "absent" ? (
                                                                <span
                                                                    className="inline-flex items-center justify-center w-7 h-7 rounded-full bg-red-100 text-red-500 font-bold text-xs cursor-pointer hover:bg-red-200 transition-colors"
                                                                    // onClick={() => updateAttendance(student.id, day.date, "present")}
                                                                >
                                                                    A
                                                                </span>
                                                            ) : (
                                                                <span
                                                                    className="inline-flex items-center justify-center w-7 h-7 rounded-full bg-gray-100 text-gray-400 font-semibold text-xs cursor-pointer hover:bg-gray-200 transition-colors"
                                                                    onClick={() => updateAttendance(student.id, day.date, "present")}
                                                                >
                                                                    -
                                                                </span>
                                                            )
                                                        ) : (
                                                            <span className="inline-flex items-center justify-center w-7 h-7 rounded-full bg-gray-50 text-gray-300 font-semibold text-xs">
                                                                -
                                                            </span>
                                                        )}
                                                    </td>
                                                );
                                            })}
                                        </tr>
                                    ))
                                )}
                            </tbody>
                        </table>
                    </div>

                    {/* Pagination */}
                    {!loading && students.length > 0 && (
                        <div className="flex flex-col sm:flex-row justify-between items-center gap-4 mt-6 pt-4 border-t">
                            <div className="text-sm text-gray-600">
                                Showing {((pagination.current_page - 1) * pagination.per_page) + 1} to{' '}
                                {Math.min(pagination.current_page * pagination.per_page, pagination.total)} of{' '}
                                {pagination.total} entries
                                <select
                                    value={perPage}
                                    onChange={handlePerPageChange}
                                    className="ml-3 px-2 py-1 border rounded-md text-sm"
                                >
                                    <option value={10}>10</option>
                                    <option value={25}>25</option>
                                    <option value={50}>50</option>
                                    <option value={100}>100</option>
                                </select>
                            </div>
                            <div className="flex gap-2">
                                <button
                                    onClick={() => handlePageChange(pagination.current_page - 1)}
                                    disabled={pagination.current_page === 1}
                                    className="w-8 h-8 flex items-center justify-center border rounded-full disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors"
                                >
                                    <IconChevronLeft className="w-4 h-4" />
                                </button>
                                <div className="flex gap-1">
                                    {(() => {
                                        const pages = [];
                                        const maxVisible = 5;
                                        let startPage = Math.max(1, pagination.current_page - Math.floor(maxVisible / 2));
                                        let endPage = Math.min(pagination.last_page, startPage + maxVisible - 1);

                                        if (endPage - startPage + 1 < maxVisible) {
                                            startPage = Math.max(1, endPage - maxVisible + 1);
                                        }

                                        for (let i = startPage; i <= endPage; i++) {
                                            pages.push(i);
                                        }

                                        return pages.map((pageNum) => (
                                            <button
                                                key={pageNum}
                                                onClick={() => handlePageChange(pageNum)}
                                                className={`w-8 h-8 flex items-center justify-center border rounded-full transition-colors ${
                                                    pagination.current_page === pageNum
                                                        ? 'bg-primary text-white border-primary'
                                                        : 'hover:bg-gray-50'
                                                }`}
                                            >
                                                {pageNum}
                                            </button>
                                        ));
                                    })()}
                                </div>
                                <button
                                    onClick={() => handlePageChange(pagination.current_page + 1)}
                                    disabled={pagination.current_page === pagination.last_page}
                                    className="w-8 h-8 flex items-center justify-center border rounded-full hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                                >
                                    <IconChevronRight className="w-4 h-4" />
                                </button>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </>
    );
};

export default StudentAttendance;
