import { useState } from 'react';
import { ModerationFilters } from './ModerationDashboard';
import { JobModerationCard } from './JobModerationCard';
import { ChevronLeft, ChevronRight, Inbox, CheckSquare, Square, X, Layers } from 'lucide-react';
import toast from 'react-hot-toast';
import { useBulkSelection } from './context/BulkSelectionContext';

interface JobModerationQueueListProps {
    jobs: any[];
    loading: boolean;
    pagination: { total: number; page: number; totalPages: number };
    filters: ModerationFilters;
    setFilters: React.Dispatch<React.SetStateAction<ModerationFilters>>;
    onRefresh: () => void;
}

export function JobModerationQueueList({ jobs, loading, pagination, filters, setFilters, onRefresh }: JobModerationQueueListProps) {
    const {
        selectedIds,
        isAllInQueueSelected,
        toggleSelection,
        setPageSelection,
        setAllInQueueSelection,
        clearSelection,
        selectedCount
    } = useBulkSelection();

    const [isBulkActionLoading, setIsBulkActionLoading] = useState(false);
    const [bulkRejectReason, setBulkRejectReason] = useState('');
    const [showBulkRejectForm, setShowBulkRejectForm] = useState(false);

    if (loading) {
        return (
            <div className="p-8 space-y-4">
                {[1, 2, 3].map((i) => (
                    <div key={i} className="h-48 bg-slate-50 rounded-xl border border-slate-200 animate-pulse"></div>
                ))}
            </div>
        );
    }

    if (!jobs || jobs.length === 0) {
        return (
            <div className="p-16 text-center">
                <div className="w-16 h-16 bg-slate-50 text-slate-300 rounded-full flex items-center justify-center mx-auto mb-4">
                    <Inbox className="w-8 h-8" />
                </div>
                <h3 className="text-lg font-medium text-slate-900">Queue is Empty</h3>
                <p className="text-slate-500 mt-1 max-w-sm mx-auto">
                    There are no jobs currently awaiting moderation that match your filters. Great job keeping the queue clean!
                </p>
                {filters.search && (
                    <button
                        onClick={() => setFilters(prev => ({ ...prev, search: '' }))}
                        className="mt-4 text-blue-600 font-medium hover:underline text-sm"
                    >
                        Clear Search
                    </button>
                )}
            </div>
        );
    }

    const handleSelectAllOnPage = (checked: boolean) => {
        setPageSelection(jobs.map(j => j.id), checked);
    };

    const handleBulkAction = async (action: 'approve' | 'reject') => {
        if (action === 'reject' && !bulkRejectReason) {
            toast.error("Please select a reason for rejection.");
            return;
        }

        const confirmMessage = action === 'approve'
            ? `Are you sure you want to approve ${selectedCount} jobs?`
            : `Are you sure you want to reject ${selectedCount} jobs?`;

        if (!confirm(confirmMessage)) return;

        setIsBulkActionLoading(true);
        const loadingToast = toast.loading(`Processing bulk ${action}...`);

        try {
            const res = await fetch('/api/admin/jobs/moderation/bulk', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    jobIds: isAllInQueueSelected ? [] : selectedIds,
                    allInQueue: isAllInQueueSelected,
                    filters: isAllInQueueSelected ? filters : undefined,
                    action,
                    notes: action === 'reject' ? `Bulk Reject: ${bulkRejectReason}` : 'Bulk Approval',
                })
            });

            const data = await res.json();

            if (res.ok) {
                toast.success(`Successfully ${action}ed ${selectedCount} jobs`, { id: loadingToast });
                clearSelection();
                setShowBulkRejectForm(false);
                setBulkRejectReason('');
                onRefresh();
            } else {
                throw new Error(data.error || `Failed to ${action} jobs`);
            }
        } catch (error: any) {
            console.error(error);
            toast.error(error.message || "An error occurred during bulk action", { id: loadingToast });
        } finally {
            setIsBulkActionLoading(false);
        }
    };

    const isPageAllSelected = jobs.length > 0 && jobs.every(j => selectedIds.includes(j.id));

    return (
        <div className="p-4 sm:p-6 space-y-4">

            {/* Select All Bar */}
            <div className="flex flex-col gap-2">
                <div className="flex items-center justify-between bg-slate-50 border border-slate-200 rounded-xl p-3">
                    <div className="flex items-center gap-3">
                        <input
                            type="checkbox"
                            checked={isPageAllSelected || isAllInQueueSelected}
                            onChange={(e) => handleSelectAllOnPage(e.target.checked)}
                            className="w-5 h-5 rounded border-slate-300 text-blue-600 focus:ring-blue-500 cursor-pointer"
                        />
                        <span className="text-sm font-medium text-slate-700">
                            Select All ({jobs.length} jobs on this page)
                        </span>
                    </div>
                    {selectedCount > 0 && (
                        <div className="flex items-center gap-3 animate-in fade-in slide-in-from-bottom-2">
                            <span className="text-sm text-slate-600 font-medium">{selectedCount} selected</span>
                            <div className="h-4 w-px bg-slate-300"></div>
                            <button
                                onClick={() => handleBulkAction('approve')}
                                disabled={isBulkActionLoading}
                                className="text-sm px-3 py-1.5 bg-green-600 text-white rounded-md font-medium hover:bg-green-700 transition disabled:opacity-50"
                            >
                                Approve All
                            </button>
                            <button
                                onClick={() => setShowBulkRejectForm(!showBulkRejectForm)}
                                disabled={isBulkActionLoading}
                                className="text-sm px-3 py-1.5 bg-white border border-red-200 text-red-600 rounded-md font-medium hover:bg-red-50 transition disabled:opacity-50"
                            >
                                Reject All
                            </button>
                        </div>
                    )}
                </div>

                {/* Select All in Queue Banner */}
                {isPageAllSelected && !isAllInQueueSelected && pagination.total > jobs.length && (
                    <div className="bg-blue-50 border border-blue-100 rounded-lg p-2.5 text-center animate-in slide-in-from-top-1">
                        <p className="text-sm text-blue-800">
                            All {jobs.length} jobs on this page are selected.
                            <button
                                onClick={() => setAllInQueueSelection(pagination.total, true)}
                                className="ml-2 font-bold hover:underline"
                            >
                                Select all {pagination.total} jobs in the moderation queue
                            </button>
                        </p>
                    </div>
                )}

                {isAllInQueueSelected && (
                    <div className="bg-blue-600 border border-blue-700 rounded-lg p-2.5 text-center animate-in slide-in-from-top-1">
                        <p className="text-sm text-white font-medium">
                            All {pagination.total} jobs in the queue are selected.
                            <button
                                onClick={() => clearSelection()}
                                className="ml-2 underline hover:text-blue-100"
                            >
                                Clear selection
                            </button>
                        </p>
                    </div>
                )}
            </div>

            {/* Bulk Reject Form Dropdown */}
            {showBulkRejectForm && selectedCount > 0 && (
                <div className="p-4 bg-red-50 border border-red-200 rounded-xl mb-4 animate-in fade-in slide-in-from-top-2">
                    <div className="flex justify-between items-start mb-3">
                        <h4 className="font-medium text-red-800">Bulk Reject {selectedCount} Jobs</h4>
                        <button onClick={() => setShowBulkRejectForm(false)} className="text-red-400 hover:text-red-700">
                            <X className="w-5 h-5" />
                        </button>
                    </div>
                    <div className="flex gap-3">
                        <select
                            className="flex-1 bg-white border border-red-200 rounded-lg text-sm p-2 text-slate-700 outline-none focus:border-red-500"
                            value={bulkRejectReason}
                            onChange={(e) => setBulkRejectReason(e.target.value)}
                        >
                            <option value="" disabled>Select global reason for rejection...</option>
                            <option value="Spam / Fraud">Spam / Fraud</option>
                            <option value="Duplicate Postings">Duplicate Postings</option>
                            <option value="Does not meet platform guidelines">Does not meet platform guidelines</option>
                        </select>
                        <button
                            onClick={() => handleBulkAction('reject')}
                            disabled={!bulkRejectReason || isBulkActionLoading}
                            className="px-4 py-2 bg-red-600 disabled:bg-red-400 text-white rounded-lg text-sm font-medium"
                        >
                            Confirm Reject All
                        </button>
                    </div>
                </div>
            )}

            {jobs.map((job) => (
                <JobModerationCard
                    key={job.id}
                    job={job}
                    onRefresh={onRefresh}
                    isSelected={selectedIds.includes(job.id) || isAllInQueueSelected}
                    onSelect={(id, checked) => toggleSelection(id)}
                />
            ))}

            {/* Pagination Controls */}
            {pagination.totalPages > 1 && (
                <div className="flex items-center justify-between border-t border-slate-200 mt-6 pt-6">
                    <div className="text-sm text-slate-500">
                        Showing <span className="font-medium text-slate-900">{((pagination.page - 1) * filters.limit) + 1}</span> to <span className="font-medium text-slate-900">{Math.min(pagination.page * filters.limit, pagination.total)}</span> of <span className="font-medium text-slate-900">{pagination.total}</span> jobs
                    </div>
                    <div className="flex items-center gap-2 text-sm font-medium">
                        <button
                            onClick={() => setFilters(prev => ({ ...prev, page: Math.max(1, prev.page - 1) }))}
                            disabled={pagination.page <= 1}
                            className="p-2 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-50 transition-colors"
                        >
                            <ChevronLeft className="w-4 h-4" />
                        </button>
                        <span className="px-4 py-2 bg-slate-50 rounded-lg text-slate-600">
                            Page {pagination.page} / {pagination.totalPages}
                        </span>
                        <button
                            onClick={() => setFilters(prev => ({ ...prev, page: Math.min(pagination.totalPages, prev.page + 1) }))}
                            disabled={pagination.page >= pagination.totalPages}
                            className="p-2 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 disabled:opacity-50 transition-colors"
                        >
                            <ChevronRight className="w-4 h-4" />
                        </button>
                    </div>
                </div>
            )}
        </div>
    );
}
