import { Link, useNavigate } from "react-router-dom";
import Button from "../../components/Buttons";
import Tabs from "../../components/Tabs";
import IconPlus from "../../components/Icon/IconPlus";
import IconBuilding from "../../components/Icon/IconBuilding";
import IconUser from "../../components/Icon/IconUser";
import IconSearch from "../../components/Icon/IconSearch";
import IconChevronLeft from "../../components/Icon/IconChevronLeft";
import IconChevronRight from "../../components/Icon/IconChevronRight";
import IconRefresh from "../../components/Icon/IconRefresh";
import { useState, useEffect, useCallback } from "react";
import api from '../../api/axios';
import { toast } from 'react-toastify';
import config from '../../config';

interface PlacedStudent {
    id: number;
    student: {
        id: number;
        name: string;
        email: string;
        phone: string;
        avatar: string;
    };
    interview: {
        id: number;
        company_name: string;
        job_role: string;
        package: string;
    };
    selected_date: string;
    status: number;
    status_text: string;
    status_color: string;
    created_at: string;
}

interface PaginationData {
    current_page: number;
    per_page: number;
    total: number;
    last_page: number;
    from: number;
    to: number;
}

function ManagePlacedStudent() {
    const navigate = useNavigate();
    const [placedStudents, setPlacedStudents] = useState<PlacedStudent[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [debouncedSearch, setDebouncedSearch] = useState('');
    const [statusFilter, setStatusFilter] = useState('');
    const [pagination, setPagination] = useState<PaginationData>({
        current_page: 1,
        per_page: 25,
        total: 0,
        last_page: 1,
        from: 0,
        to: 0
    });

    const tabData = [
        { id: 'Manage Interview', label: 'Manage Interview', path: '/manage_placements' },
        { id: 'Alumni', label: 'Alumni', path: '/manage_alumni' },
        { id: 'Placed Student', label: 'Placed Student', path: '/manage_placed_student' },
    ];

    const statusOptions = [
        { value: '', label: 'All Status' },
        { value: '1', label: 'Shortlisted' },
        { value: '2', label: 'Selected' },
        { value: '3', label: 'Joined' },
        { value: '4', label: 'Rejected' }
    ];

    // Debounce search
    useEffect(() => {
        const timer = setTimeout(() => {
            setDebouncedSearch(searchTerm);
        }, 500);
        return () => clearTimeout(timer);
    }, [searchTerm]);

    // Fetch placed students
    const fetchPlacedStudents = useCallback(async () => {
        setLoading(true);
        try {
            const params = new URLSearchParams({
                page: pagination.current_page.toString(),
                per_page: pagination.per_page.toString(),
                search: debouncedSearch,
                ...(statusFilter && { status: statusFilter })
            });

            const response = await api.get(`/placement/placed-students?${params}`);

            if (response.data.status) {
                setPlacedStudents(response.data.data.data);
                setPagination({
                    current_page: response.data.data.current_page,
                    per_page: response.data.data.per_page,
                    total: response.data.data.total,
                    last_page: response.data.data.last_page,
                    from: response.data.data.from,
                    to: response.data.data.to
                });
            }
        } catch (error) {
            console.error('Failed to fetch placed students:', error);
            toast.error('Failed to load placed students');
        } finally {
            setLoading(false);
        }
    }, [pagination.current_page, pagination.per_page, debouncedSearch, statusFilter]);

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

    const handlePageChange = (page: number) => {
        if (page >= 1 && page <= pagination.last_page) {
            setPagination(prev => ({ ...prev, current_page: page }));
        }
    };

    const handlePerPageChange = (perPage: number) => {
        setPagination(prev => ({ ...prev, per_page: perPage, current_page: 1 }));
    };

    const handleSearch = (val: string) => {
        setSearchTerm(val);
        setPagination(prev => ({ ...prev, current_page: 1 }));
    };

    const handleRefresh = () => {
        setSearchTerm('');
        setDebouncedSearch('');
        setStatusFilter('');
        setPagination(prev => ({ ...prev, current_page: 1 }));
    };

    const storageBaseUrl = config.storageUrl;

    const getImageUrl = (imagePath: string | null): string => {
        if (!imagePath) return `https://ui-avatars.com/api/?background=6366f1&color=fff&name=${encodeURIComponent('Student')}`;
        if (imagePath.startsWith('http://') || imagePath.startsWith('https://')) {
            return imagePath;
        }
        return `${storageBaseUrl}/${imagePath}`;
    };

    // Skeleton Loader Card
    const SkeletonCard = () => (
        <div className="col-span-12 md:col-span-6 lg:col-span-4 animate-pulse">
            <div className="p-4 border rounded-xl">
                <div className="grid grid-cols-12 gap-3">
                    <div className="col-span-12">
                        <div className="flex items-start gap-2">
                            <div className="p-2 rounded-xl bg-gray-200 w-10 h-10"></div>
                            <div className="flex flex-col gap-2 flex-1">
                                <div className="h-4 bg-gray-200 rounded w-32"></div>
                                <div className="h-3 bg-gray-200 rounded w-24"></div>
                            </div>
                        </div>
                    </div>
                    <div className="col-span-6">
                        <div className="p-2 bg-gray-50 flex flex-col gap-1">
                            <div className="h-3 bg-gray-200 rounded w-16"></div>
                            <div className="h-4 bg-gray-200 rounded w-20"></div>
                        </div>
                    </div>
                    <div className="col-span-6">
                        <div className="p-2 bg-gray-50 flex flex-col gap-1">
                            <div className="h-3 bg-gray-200 rounded w-20"></div>
                            <div className="h-4 bg-gray-200 rounded w-24"></div>
                        </div>
                    </div>
                    <div className="col-span-12">
                        <div className="p-2 rounded bg-gray-50 flex gap-3 items-center">
                            <div className="w-5 h-5 bg-gray-200 rounded"></div>
                            <div className="flex flex-col gap-1 flex-1">
                                <div className="h-3 bg-gray-200 rounded w-16"></div>
                                <div className="h-4 bg-gray-200 rounded w-32"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );

    // Get status badge color
    const getStatusBadge = (status: string, statusColor: string) => {
        return (
            <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${statusColor}`}>
                {status}
            </span>
        );
    };

    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_placements" className="text-primary text-lg hover:underline">
                            Manage Placement
                        </Link>
                    </li>
                    <li className="before:content-['/'] ml-2">
                        <span>Placed Students</span>
                    </li>
                </ul>
            </div>

            <Tabs
                tabs={tabData}
                defaultTab="Placed Student"
                onChange={(tabId) => {
                    const selectedTab = tabData.find(t => t.id === tabId);
                    if (selectedTab?.path) {
                        navigate(selectedTab.path);
                    }
                }}
            />

            <div className="pt-4">
                <div className="p-4 rounded-xl bg-white w-full max-w-full overflow-hidden">
                    {/* Filters */}
                    <div className="flex flex-wrap justify-between items-center gap-4 mb-6">
                        <div className="flex-1 min-w-[250px]">
                            <div className="relative">
                                <input
                                    type="text"
                                    placeholder="Search by Student Name, Company, Job Role..."
                                    value={searchTerm}
                                    onChange={(e) => handleSearch(e.target.value)}
                                    className="w-full border rounded-lg px-4 py-2 pl-10 focus:outline-none focus:ring-2 focus:ring-primary"
                                />
                                <IconSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                            </div>
                        </div>

                        {/* <div className="flex gap-3">
                            <select
                                value={statusFilter}
                                onChange={(e) => {
                                    setStatusFilter(e.target.value);
                                    setPagination(prev => ({ ...prev, current_page: 1 }));
                                }}
                                className="border rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary"
                            >
                                {statusOptions.map(option => (
                                    <option key={option.value} value={option.value}>
                                        {option.label}
                                    </option>
                                ))}
                            </select>

                            <Button
                                variant="primary"
                                onClick={handleRefresh}
                                icon={<IconRefresh />}
                            >
                                Refresh
                            </Button>
                        </div> */}
                    </div>

                    {/* Placed Students Grid */}
                    <div className="grid grid-cols-12 gap-4">
                        {loading ? (
                            // Show skeleton loading
                            Array.from({ length: pagination.per_page }).map((_, index) => (
                                <SkeletonCard key={index} />
                            ))
                        ) : placedStudents.length === 0 ? (
                            <div className="col-span-12 text-center py-12">
                                <div className="text-gray-400 text-lg">No placed students found</div>
                                <p className="text-gray-400 text-sm mt-2">Try adjusting your search or filter</p>
                            </div>
                        ) : (
                            placedStudents.map((student) => (
                                <div key={student.id} className="col-span-12 md:col-span-6 lg:col-span-4">
                                    <div className="p-4 border rounded-xl hover:shadow-lg transition-all duration-300">
                                        <div className="grid grid-cols-12 gap-3">
                                            <div className="col-span-12">
                                                <div className="flex items-start justify-between gap-2">
                                                    <div className="flex items-start gap-2 flex-1">
                                                        <div className='p-2 rounded-xl bg-[#FCE7F3] text-primary'>
                                                            <IconUser />
                                                        </div>
                                                        <div className='flex flex-col flex-1'>
                                                            <div className="flex items-center justify-between">
                                                                <label className='font-semibold text-sm mb-0'>
                                                                    {student.student.name}
                                                                </label>
                                                            </div>
                                                            <label className='text-xs mb-0 text-pink-500'>
                                                                {student.interview.job_role}
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div className="col-span-6">
                                                <div className="p-2 bg-gray-50 rounded-lg flex flex-col">
                                                    <label className="text-gray-400 text-xs mb-0">Package</label>
                                                    <label className="text-black text-sm mb-0 font-semibold">
                                                        {student.interview.package}
                                                    </label>
                                                </div>
                                            </div>

                                            <div className="col-span-6">
                                                <div className="p-2 bg-gray-50 rounded-lg flex flex-col">
                                                    <label className="text-gray-400 text-xs mb-0">Joined Date</label>
                                                    <label className="text-black mb-0 text-sm">
                                                        {student.selected_date || 'Not specified'}
                                                    </label>
                                                </div>
                                            </div>

                                            <div className="col-span-12">
                                                <div className="p-2 rounded-lg bg-gray-50 flex gap-3 items-center">
                                                    <IconBuilding className="text-gray-900 w-5 h-5" />
                                                    <div className="flex flex-col">
                                                        <label className="text-gray-400 text-xs mb-0">Company</label>
                                                        <label className="text-black mb-0 text-sm font-medium">
                                                            {student.interview.company_name}
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ))
                        )}
                    </div>

                    {/* Pagination */}
                    {!loading && placedStudents.length > 0 && (
                        <div className="flex flex-col sm:flex-row justify-between items-center gap-4 mt-8 pt-6 border-t">
                            {/* Left side - Showing entries */}
                            <div className="text-sm text-gray-600">
                                Showing <strong>{pagination.from}</strong> to <strong>{pagination.to}</strong> of{' '}
                                <strong>{pagination.total}</strong> entries
                            </div>

                            {/* Right side - Per page and pagination */}
                            <div className="flex items-center gap-4 flex-wrap justify-center">
                                {/* Per Page Selector */}
                                <div className="flex items-center gap-2">
                                    <select
                                        value={pagination.per_page}
                                        onChange={(e) => handlePerPageChange(Number(e.target.value))}
                                        className="border rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-primary"
                                    >
                                        <option value="10">10</option>
                                        <option value="25">25</option>
                                        <option value="50">50</option>
                                        <option value="100">100</option>
                                    </select>
                                </div>

                                {/* Pagination Controls */}
                                <div className="flex gap-2 items-center">
                                    <button
                                        onClick={() => handlePageChange(pagination.current_page - 1)}
                                        disabled={pagination.current_page === 1}
                                        className="w-9 h-9 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>

                                    {/* Page Numbers */}
                                    <div className="flex gap-1">
                                        {(() => {
                                            const pages: number[] = [];
                                            const totalPages = pagination.last_page;
                                            const currentPage = pagination.current_page;

                                            if (totalPages <= 7) {
                                                for (let i = 1; i <= totalPages; i++) {
                                                    pages.push(i);
                                                }
                                            } else {
                                                pages.push(1);
                                                if (currentPage > 4) pages.push(-1);
                                                const start = Math.max(2, currentPage - 1);
                                                const end = Math.min(totalPages - 1, currentPage + 1);
                                                for (let i = start; i <= end; i++) {
                                                    pages.push(i);
                                                }
                                                if (currentPage < totalPages - 3) pages.push(-1);
                                                pages.push(totalPages);
                                            }

                                            return pages.map((page, index) => {
                                                if (page === -1) {
                                                    return (
                                                        <span
                                                            key={`ellipsis-${index}`}
                                                            className="w-9 h-9 flex items-center justify-center text-gray-400"
                                                        >
                                                            ...
                                                        </span>
                                                    );
                                                }
                                                return (
                                                    <button
                                                        key={page}
                                                        onClick={() => handlePageChange(page)}
                                                        className={`w-9 h-9 flex items-center justify-center border rounded-full text-sm font-medium transition-colors ${
                                                            pagination.current_page === page
                                                                ? 'bg-primary text-white shadow-md shadow-primary/30'
                                                                : 'border hover:bg-gray-50 hover:border-primary/50'
                                                        }`}
                                                    >
                                                        {page}
                                                    </button>
                                                );
                                            });
                                        })()}
                                    </div>

                                    <button
                                        onClick={() => handlePageChange(pagination.current_page + 1)}
                                        disabled={pagination.current_page === pagination.last_page}
                                        className="w-9 h-9 flex items-center justify-center border rounded-full disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 transition-colors"
                                    >
                                        <IconChevronRight className="w-4 h-4" />
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}

export default ManagePlacedStudent;
