'use client';

import { useState } from 'react';
import {
    X, Edit3, Sparkles, MessageSquare,
    CheckSquare, Square, ChevronRight,
    ChevronLeft, Loader2, Send, AlertCircle
} from 'lucide-react';
import { motion, AnimatePresence } from 'framer-motion';
import { useBulkSelection } from '../../context/BulkSelectionContext';
import { cn } from '@/lib/utils';

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

const COMMON_ISSUES = [
    { id: 'salary', label: 'Salary transparency required' },
    { id: 'desc', label: 'Expand job description' },
    { id: 'skills', label: 'Requirements are too vague' },
    { id: 'formatting', label: 'Improve text formatting/layout' },
    { id: 'location', label: 'Invalid or missing location' },
    { id: 'links', label: 'Dead or suspicious external links' }
];

export function BulkRequestChangesModal({ isOpen, onClose, onRequestChanges, isProcessing }: BulkRequestChangesModalProps) {
    const { selectedCount } = useBulkSelection();
    const [step, setStep] = useState(0);

    // Form State
    const [selectedIssues, setSelectedIssues] = useState<string[]>([]);
    const [globalMessage, setGlobalMessage] = useState('');
    const [useAI, setUseAI] = useState(true);
    const [isGenerating, setIsGenerating] = useState(false);

    if (!isOpen) return null;

    const toggleIssue = (id: string) => {
        setSelectedIssues(prev =>
            prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
        );
    };

    const handleGenerateDrafts = () => {
        setIsGenerating(true);
        setTimeout(() => {
            setIsGenerating(false);
            setStep(1);
        }, 2000);
    };

    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-indigo-50/50">
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 bg-indigo-100 text-indigo-600 rounded-xl flex items-center justify-center">
                            <Edit3 size={24} />
                        </div>
                        <div>
                            <h2 className="text-xl font-extrabold text-slate-900">Batch Revision Requests</h2>
                            <p className="text-sm text-indigo-700 font-bold uppercase tracking-wider text-[10px]">
                                AI-Guided Feedback for {selectedCount} Jobs
                            </p>
                        </div>
                    </div>
                    <button onClick={onClose} className="p-2 hover:bg-slate-200 rounded-full transition-colors">
                        <X size={20} />
                    </button>
                </div>

                <div className="flex-1 overflow-y-auto p-8">
                    <AnimatePresence mode="wait">
                        {step === 0 ? (
                            <motion.div
                                key="setup"
                                initial={{ opacity: 0, x: -20 }}
                                animate={{ opacity: 1, x: 0 }}
                                exit={{ opacity: 0, x: 20 }}
                                className="space-y-8"
                            >
                                {/* Common Issues */}
                                <div className="space-y-4">
                                    <h3 className="text-sm font-black text-slate-400 uppercase tracking-widest">Select Common Faults</h3>
                                    <div className="grid grid-cols-2 gap-3">
                                        {COMMON_ISSUES.map((issue) => (
                                            <button
                                                key={issue.id}
                                                onClick={() => toggleIssue(issue.id)}
                                                className={cn(
                                                    "flex items-center gap-3 p-3 rounded-xl border-2 transition-all text-left",
                                                    selectedIssues.includes(issue.id) ? "border-indigo-600 bg-indigo-50" : "border-slate-100 hover:border-slate-200"
                                                )}
                                            >
                                                {selectedIssues.includes(issue.id) ? (
                                                    <CheckSquare size={18} className="text-indigo-600" />
                                                ) : (
                                                    <Square size={18} className="text-slate-300" />
                                                )}
                                                <span className="text-sm font-bold text-slate-700">{issue.label}</span>
                                            </button>
                                        ))}
                                    </div>
                                </div>

                                {/* Global Guidance */}
                                <div className="space-y-4">
                                    <h3 className="text-sm font-black text-slate-400 uppercase tracking-widest">Base Instructions</h3>
                                    <textarea
                                        value={globalMessage}
                                        onChange={(e) => setGlobalMessage(e.target.value)}
                                        placeholder="Add any specific context that should be applied to all rejection messages..."
                                        className="w-full bg-slate-50 border-2 border-slate-100 rounded-2xl p-4 h-32 focus:bg-white focus:border-indigo-500 outline-none transition-all text-sm font-medium"
                                    />
                                </div>

                                <div className="p-4 bg-slate-900 rounded-2xl flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <div className="w-8 h-8 bg-indigo-500/20 text-indigo-400 rounded-lg flex items-center justify-center">
                                            <Sparkles size={16} />
                                        </div>
                                        <div className="text-left">
                                            <p className="text-xs font-bold text-white">AI Personalization Engine</p>
                                            <p className="text-[10px] text-slate-400">Generate distinct drafts for each posting</p>
                                        </div>
                                    </div>
                                    <button
                                        onClick={() => setUseAI(!useAI)}
                                        className={cn(
                                            "w-10 h-6 rounded-full transition-all relative",
                                            useAI ? "bg-indigo-600" : "bg-slate-700"
                                        )}
                                    >
                                        <div className={cn("absolute top-1 w-4 h-4 bg-white rounded-full transition-all", useAI ? "left-5" : "left-1")} />
                                    </button>
                                </div>
                            </motion.div>
                        ) : (
                            <motion.div
                                key="preview"
                                initial={{ opacity: 0, x: 20 }}
                                animate={{ opacity: 1, x: 0 }}
                                className="space-y-6"
                            >
                                <div className="p-4 bg-indigo-600 text-white rounded-2xl flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <MessageSquare size={20} />
                                        <span className="text-sm font-bold">Drafts for {selectedCount} Employers Generated</span>
                                    </div>
                                    <span className="text-[10px] bg-white/20 px-2 py-1 rounded font-black uppercase tracking-widest">Reviewing Batch</span>
                                </div>

                                <div className="space-y-3">
                                    {[1, 2, 3].map((i) => (
                                        <div key={i} className="p-4 border border-slate-200 rounded-2xl bg-white opacity-90 hover:opacity-100 transition-opacity">
                                            <div className="flex justify-between items-start mb-2">
                                                <h4 className="text-xs font-black uppercase text-indigo-600 tracking-wider">Example Draft {i}</h4>
                                                <AlertCircle size={14} className="text-slate-300" />
                                            </div>
                                            <p className="text-xs text-slate-500 italic">"We've reviewed your posting for [Position]. Please expand the requirements section as it is currently too brief for our platform guidelines..."</p>
                                        </div>
                                    ))}
                                    {selectedCount > 3 && (
                                        <div className="text-center py-2">
                                            <span className="text-xs text-slate-400 font-bold">+ {selectedCount - 3} more tailored drafts</span>
                                        </div>
                                    )}
                                </div>
                            </motion.div>
                        )}
                    </AnimatePresence>
                </div>

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

                    {step === 0 ? (
                        <button
                            onClick={handleGenerateDrafts}
                            disabled={selectedIssues.length === 0 || isGenerating}
                            className="flex-1 max-w-[240px] flex items-center justify-center gap-2 px-6 py-4 bg-indigo-600 disabled:bg-slate-200 text-white rounded-2xl font-black uppercase text-lg hover:bg-indigo-700 transition-all shadow-xl shadow-indigo-100 active:scale-95 disabled:shadow-none"
                        >
                            {isGenerating ? (
                                <Loader2 className="animate-spin" />
                            ) : (
                                <>
                                    Draft Feedback
                                    <Sparkles size={20} />
                                </>
                            )}
                        </button>
                    ) : (
                        <button
                            onClick={() => onRequestChanges({ selectedIssues, globalMessage, useAI })}
                            disabled={isProcessing}
                            className="flex-1 max-w-[240px] flex items-center justify-center gap-2 px-6 py-4 bg-slate-900 disabled:bg-slate-400 text-white rounded-2xl font-black uppercase text-lg hover:bg-black transition-all shadow-xl active:scale-95"
                        >
                            {isProcessing ? (
                                <Loader2 className="animate-spin" />
                            ) : (
                                <>
                                    Send Requests
                                    <Send size={20} />
                                </>
                            )}
                        </button>
                    )}
                </div>
            </motion.div>
        </div>
    );
}
