'use client';

import { useState } from 'react';
import {
    X, AlertTriangle, Shield, ShieldX, Ghost,
    Layers, Search, CheckCircle2, AlertOctagon,
    Lock, ChevronRight, ChevronLeft, Fingerprint
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { useBulkSelection } from '../../context/BulkSelectionContext';
import { cn } from '@/lib/utils';

interface BulkRejectModalProps {
    isOpen: boolean;
    onClose: () => void;
    onReject: (data: any) => Promise<void>;
    isProcessing: boolean;
}

const STEPS = [
    { id: 'category', title: 'Global Reason' },
    { id: 'patterns', title: 'Pattern Detection' },
    { id: 'severity', title: 'Action Severity' },
    { id: 'confirm', title: 'Safety Check' }
];

const REJECTION_CATEGORIES = [
    { id: 'spam', label: 'Spam / Commercial advertising', icon: ShieldX, color: 'text-red-600' },
    { id: 'fraud', label: 'Potential Fraud / Phishing', icon: AlertOctagon, color: 'text-red-700' },
    { id: 'quality', label: 'Low Quality / Gibberish', icon: AlertTriangle, color: 'text-orange-600' },
    { id: 'duplicate', label: 'Massive Duplication', icon: Layers, color: 'text-blue-600' },
    { id: 'violation', label: 'Policy Violation', icon: Shield, color: 'text-purple-600' }
];

const MOCK_PATTERNS = [
    { id: 1, title: 'Identical Metadata', description: '80% of jobs share the same posting IP address.', probability: 98 },
    { id: 2, title: 'NLP Script Matching', description: 'Job descriptions generated from the same template.', probability: 92 },
    { id: 3, title: 'Rapid Posting', description: 'All selected jobs posted within 12 seconds.', probability: 85 }
];

export function BulkRejectModal({ isOpen, onClose, onReject, isProcessing }: BulkRejectModalProps) {
    const { selectedCount, isAllInQueueSelected } = useBulkSelection();
    const [step, setStep] = useState(0);

    // Form State
    const [category, setCategory] = useState('');
    const [selectedPatterns, setSelectedPatterns] = useState<number[]>([1, 2]);
    const [severity, setSeverity] = useState('hard'); // soft, hard, ban
    const [confirmText, setConfirmText] = useState('');
    const [password, setPassword] = useState('');

    if (!isOpen) return null;

    const nextStep = () => setStep(s => Math.min(s + 1, STEPS.length - 1));
    const prevStep = () => setStep(s => Math.max(s - 1, 0));

    const handleSubmit = async () => {
        await onReject({
            category,
            patterns: selectedPatterns,
            severity,
            confirmText
        });
    };

    const isStepValid = () => {
        if (step === 0) return !!category;
        if (step === 1) return true;
        if (step === 2) return !!severity;
        if (step === 3) return confirmText === 'REJECT ALL' && (severity !== 'ban' || password === 'admin123');
        return false;
    };

    return (
        <div className="fixed inset-0 z-[60] flex items-center justify-center p-4 bg-slate-900/80 backdrop-blur-sm">
            <motion.div
                initial={{ scale: 0.9, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                className="bg-white rounded-3xl shadow-2xl w-full max-w-2xl overflow-hidden flex flex-col max-h-[90vh]"
            >
                {/* Header */}
                <div className="p-6 border-b border-slate-100 flex items-center justify-between bg-slate-50">
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-red-100 text-red-600 rounded-xl flex items-center justify-center">
                            <XCircle size={24} className="LucideXCircle" />
                        </div>
                        <div>
                            <h2 className="text-xl font-bold text-slate-900">Bulk Rejection Workflow</h2>
                            <p className="text-sm text-slate-500 font-medium">Batch processing {selectedCount} active listings</p>
                        </div>
                    </div>
                    <button onClick={onClose} className="p-2 hover:bg-slate-200 rounded-full transition-colors">
                        <X size={20} />
                    </button>
                </div>

                {/* Progress Bar */}
                <div className="flex border-b border-slate-100">
                    {STEPS.map((s, idx) => (
                        <div
                            key={s.id}
                            className={cn(
                                "flex-1 py-3 px-1 text-center border-b-2 transition-all duration-300",
                                step === idx ? "border-red-600 text-red-600" :
                                    step > idx ? "border-green-500 text-green-500" : "border-transparent text-slate-400"
                            )}
                        >
                            <span className="text-[10px] font-bold uppercase tracking-wider">{s.title}</span>
                        </div>
                    ))}
                </div>

                {/* Content Area */}
                <div className="flex-1 overflow-y-auto p-8">
                    <AnimatePresence mode="wait">
                        {step === 0 && (
                            <motion.div
                                key="step0"
                                initial={{ x: 20, opacity: 0 }}
                                animate={{ x: 0, opacity: 1 }}
                                exit={{ x: -20, opacity: 0 }}
                                className="space-y-6"
                            >
                                <div className="space-y-4">
                                    <h3 className="text-lg font-bold text-slate-900">Select Primary Cluster Category</h3>
                                    <p className="text-sm text-slate-500 mb-6">Choose the violation policy that best describes this batch of job postings.</p>

                                    <div className="grid grid-cols-1 gap-3">
                                        {REJECTION_CATEGORIES.map((cat) => (
                                            <button
                                                key={cat.id}
                                                onClick={() => setCategory(cat.id)}
                                                className={cn(
                                                    "flex items-center gap-4 p-4 rounded-2xl border-2 transition-all text-left",
                                                    category === cat.id ? "border-red-600 bg-red-50" : "border-slate-100 hover:border-slate-300"
                                                )}
                                            >
                                                <div className={cn("p-2 rounded-lg bg-white shadow-sm", cat.color)}>
                                                    <cat.icon size={20} />
                                                </div>
                                                <span className="font-bold text-slate-800">{cat.label}</span>
                                            </button>
                                        ))}
                                    </div>
                                </div>
                            </motion.div>
                        )}

                        {step === 1 && (
                            <motion.div
                                key="step1"
                                initial={{ x: 20, opacity: 0 }}
                                animate={{ x: 0, opacity: 1 }}
                                exit={{ x: -20, opacity: 0 }}
                                className="space-y-6"
                            >
                                <div className="flex items-center gap-2 mb-4 p-4 bg-blue-50 text-blue-800 rounded-2xl border border-blue-100">
                                    <Fingerprint size={20} />
                                    <span className="text-sm font-bold">AI Pattern Detection Active</span>
                                </div>

                                <h3 className="text-lg font-bold text-slate-900">Matched Abnormalities</h3>
                                <p className="text-sm text-slate-500">The following commonalities were identified across this batch of {selectedCount} jobs.</p>

                                <div className="space-y-3">
                                    {MOCK_PATTERNS.map((p) => (
                                        <div
                                            key={p.id}
                                            className="p-4 rounded-2xl border border-slate-200 bg-white"
                                        >
                                            <div className="flex justify-between items-start mb-2">
                                                <h4 className="font-bold text-slate-800">{p.title}</h4>
                                                <span className="text-[10px] font-bold bg-slate-100 px-2 py-1 rounded text-slate-500">{p.probability}% MATCH</span>
                                            </div>
                                            <p className="text-sm text-slate-500">{p.description}</p>
                                        </div>
                                    ))}
                                </div>
                                <div className="mt-6 flex items-center gap-2 text-slate-500">
                                    <Search size={16} />
                                    <span className="text-xs italic">Searching for deeper linkages in employer activity...</span>
                                </div>
                            </motion.div>
                        )}

                        {step === 2 && (
                            <motion.div
                                key="step2"
                                initial={{ x: 20, opacity: 0 }}
                                animate={{ x: 0, opacity: 1 }}
                                exit={{ x: -20, opacity: 0 }}
                                className="space-y-6"
                            >
                                <h3 className="text-lg font-bold text-slate-900">Define Rejection Severity</h3>
                                <p className="text-sm text-slate-500">Determine how strict the enforcement should be for the associated employer(s).</p>

                                <div className="grid grid-cols-1 gap-4 mt-6">
                                    <button
                                        onClick={() => setSeverity('soft')}
                                        className={cn(
                                            "flex items-start gap-4 p-5 rounded-2xl border-2 transition-all text-left",
                                            severity === 'soft' ? "border-blue-600 bg-blue-50" : "border-slate-100"
                                        )}
                                    >
                                        <div className="p-3 bg-white rounded-xl shadow-sm text-blue-600">
                                            <Layers size={24} />
                                        </div>
                                        <div>
                                            <h4 className="font-bold text-slate-900">Soft Rejection</h4>
                                            <p className="text-xs text-slate-500 mt-1">Jobs are hidden. Employers are notified and can edit/resubmit with no penalty.</p>
                                        </div>
                                    </button>

                                    <button
                                        onClick={() => setSeverity('hard')}
                                        className={cn(
                                            "flex items-start gap-4 p-5 rounded-2xl border-2 transition-all text-left",
                                            severity === 'hard' ? "border-orange-600 bg-orange-50" : "border-slate-100"
                                        )}
                                    >
                                        <div className="p-3 bg-white rounded-xl shadow-sm text-orange-600">
                                            <AlertTriangle size={24} />
                                        </div>
                                        <div>
                                            <h4 className="font-bold text-slate-900">Hard Rejection</h4>
                                            <p className="text-xs text-slate-500 mt-1">Jobs are deleted. Employer accounts are flagged for closer manual monitoring.</p>
                                        </div>
                                    </button>

                                    <button
                                        onClick={() => setSeverity('ban')}
                                        className={cn(
                                            "flex items-start gap-4 p-5 rounded-2xl border-2 transition-all text-left",
                                            severity === 'ban' ? "border-red-600 bg-red-50" : "border-slate-100"
                                        )}
                                    >
                                        <div className="p-3 bg-white rounded-xl shadow-sm text-red-600">
                                            <ShieldX size={24} />
                                        </div>
                                        <div>
                                            <h4 className="font-bold text-slate-900">Permanent Ban</h4>
                                            <p className="text-xs text-slate-500 mt-1">Jobs purged. **Employer accounts suspended immediately**. Requires password.</p>
                                        </div>
                                    </button>
                                </div>
                            </motion.div>
                        )}

                        {step === 3 && (
                            <motion.div
                                key="step3"
                                initial={{ x: 20, opacity: 0 }}
                                animate={{ x: 0, opacity: 1 }}
                                exit={{ x: -20, opacity: 0 }}
                                className="space-y-6"
                            >
                                <div className="p-6 bg-red-900 text-white rounded-3xl space-y-4">
                                    <div className="flex items-center gap-3">
                                        <AlertTriangle size={32} />
                                        <h3 className="text-xl font-black uppercase italic">Critical Confirmation</h3>
                                    </div>
                                    <p className="text-sm opacity-90 leading-relaxed font-bold">
                                        You are about to bulk {severity === 'ban' ? 'BAN & PURGE' : 'REJECT'} {selectedCount} jobs.
                                        This action will affect {isAllInQueueSelected ? 'EVERY' : 'selected'} matching listing in the database.
                                    </p>
                                </div>

                                <div className="space-y-4 mt-6">
                                    <div>
                                        <label className="text-xs font-black text-slate-400 uppercase tracking-widest block mb-2">Type "REJECT ALL" to confirm</label>
                                        <input
                                            type="text"
                                            value={confirmText}
                                            onChange={(e) => setConfirmText(e.target.value.toUpperCase())}
                                            placeholder="REJECT ALL"
                                            className="w-full bg-slate-50 border-2 border-slate-100 rounded-2xl p-4 font-bold text-slate-900 outline-none focus:border-red-600 focus:bg-white transition-all uppercase"
                                        />
                                    </div>

                                    {severity === 'ban' && (
                                        <div className="animate-in fade-in slide-in-from-top-4">
                                            <label className="text-xs font-black text-red-600 uppercase tracking-widest block mb-2 flex items-center gap-2">
                                                <Lock size={12} />
                                                Auth Password Required for Ban
                                            </label>
                                            <input
                                                type="password"
                                                autoFocus
                                                value={password}
                                                onChange={(e) => setPassword(e.target.value)}
                                                placeholder="••••••••"
                                                className="w-full bg-slate-50 border-2 border-red-100 rounded-2xl p-4 font-bold text-slate-900 outline-none focus:border-red-600 focus:bg-white transition-all"
                                            />
                                        </div>
                                    )}
                                </div>
                            </motion.div>
                        )}
                    </AnimatePresence>
                </div>

                {/* Footer */}
                <div className="p-6 border-t border-slate-100 flex items-center justify-between gap-4 bg-slate-50">
                    {step > 0 ? (
                        <button
                            onClick={prevStep}
                            className="flex items-center gap-2 px-6 py-3 border-2 border-slate-200 text-slate-600 rounded-2xl font-bold hover:bg-slate-100 transition-all"
                        >
                            <ChevronLeft size={20} />
                            Back
                        </button>
                    ) : (
                        <button
                            onClick={onClose}
                            className="px-6 py-3 text-slate-500 font-bold hover:bg-slate-100 rounded-2xl transition-all"
                        >
                            Cancel
                        </button>
                    )}

                    {step < STEPS.length - 1 ? (
                        <button
                            onClick={nextStep}
                            disabled={!isStepValid()}
                            className="flex-1 flex items-center justify-center gap-2 px-6 py-3 bg-slate-900 disabled:bg-slate-200 text-white rounded-2xl font-bold hover:bg-slate-800 transition-all disabled:text-slate-400"
                        >
                            Continue
                            <ChevronRight size={20} />
                        </button>
                    ) : (
                        <button
                            onClick={handleSubmit}
                            disabled={!isStepValid() || isProcessing}
                            className="flex-1 flex items-center justify-center gap-2 px-6 py-3 bg-red-600 disabled:bg-red-200 text-white rounded-2xl font-black uppercase text-lg hover:bg-red-700 transition-all shadow-lg shadow-red-200 active:scale-95"
                        >
                            {isProcessing ? (
                                <span className="flex items-center gap-2">
                                    <div className="w-5 h-5 border-2 border-white/20 border-t-white rounded-full animate-spin" />
                                    Processing Batch...
                                </span>
                            ) : (
                                <>
                                    Confirm Batch Rejection
                                    <CheckCircle2 size={24} />
                                </>
                            )}
                        </button>
                    )}
                </div>
            </motion.div>
        </div>
    );
}

// Icons shim for some reason Lucide icons can be weird in some environments
function XCircle({ size, className }: { size: number, className: string }) {
    return <XCircleOriginal size={size} className={className} />;
}
import { XCircle as XCircleOriginal } from 'lucide-react';
