import { useState, useEffect } from "react";
import Image from "next/image";
import { formatDistanceToNow } from "date-fns";
import { X, CheckCircle, XCircle, AlertTriangle, MessageSquare, MapPin, Briefcase, DollarSign, ExternalLink } from "lucide-react";
import { JobDetailsTab } from "./tabs/JobDetailsTab";
import { CompanyProfileTab } from "./tabs/CompanyProfileTab";
import { JobHistoryTab } from "./tabs/JobHistoryTab";
import { AIAnalysisTab } from "./tabs/AIAnalysisTab";

interface JobReviewModalProps {
    job: any;
    isOpen: boolean;
    onClose: () => void;
    onApprove: () => void;
    onRejectClick: () => void; // Opens the rejection form from the parent
    actionLoading: boolean;
}

type TabType = 'details' | 'company' | 'history' | 'ai_analysis' | 'similar_jobs';

export function JobReviewModal({ job, isOpen, onClose, onApprove, onRejectClick, actionLoading }: JobReviewModalProps) {
    const [activeTab, setActiveTab] = useState<TabType>('details');

    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape' && isOpen) onClose();
        };
        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [isOpen, onClose]);

    if (!isOpen || !job) return null;

    return (
        <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 sm:p-6">
            <div className="absolute inset-0 bg-slate-900/60 backdrop-blur-sm" onClick={onClose} />

            <div className="relative w-full max-w-5xl bg-white rounded-2xl shadow-2xl flex flex-col max-h-[90vh] overflow-hidden animate-in fade-in zoom-in-95 duration-200">

                {/* Header Profile Banner */}
                <div className="flex-shrink-0 border-b border-slate-200 bg-slate-50 p-6">
                    <button
                        onClick={onClose}
                        className="absolute right-6 top-6 p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-200 rounded-full transition-colors"
                    >
                        <X className="w-5 h-5" />
                    </button>

                    <div className="flex items-start gap-6 pr-12">
                        <div className="w-16 h-16 rounded-xl bg-white border border-slate-200 flex items-center justify-center overflow-hidden relative shrink-0 shadow-sm">
                            {job.employer?.avatar_url ? (
                                <Image src={job.employer.avatar_url} alt={job.company} fill className="object-cover" />
                            ) : (
                                <span className="text-2xl font-bold text-slate-400">{job.company?.charAt(0) || 'C'}</span>
                            )}
                        </div>
                        <div className="flex-1">
                            <h2 className="text-2xl font-bold text-slate-900">{job.title}</h2>
                            <div className="flex flex-wrap items-center gap-3 mt-2 text-sm text-slate-600">
                                <span className="font-semibold text-slate-800">{job.company}</span>
                                <span>•</span>
                                <span className="flex items-center gap-1.5"><MapPin className="w-4 h-4 text-slate-400" /> {job.work_location_type === 'remote' ? 'Remote' : (job.city || job.address || 'Location Unspecified')}</span>
                                <span>•</span>
                                <span className="flex items-center gap-1.5"><Briefcase className="w-4 h-4 text-slate-400" /> <span className="capitalize">{job.type.replace('-', ' ')}</span></span>
                                <span>•</span>
                                <span className="flex items-center gap-1.5"><DollarSign className="w-4 h-4 text-slate-400" /> {job.hide_salary ? 'Hidden' : (job.salary_min ? `${job.currency} ${job.salary_min.toLocaleString()}` : 'Not Specified')}</span>
                            </div>
                        </div>
                    </div>

                    {/* Action Bar (Top Right) */}
                    <div className="absolute right-6 bottom-4 flex items-center gap-3 hidden md:flex">
                        <button
                            onClick={onRejectClick}
                            disabled={actionLoading}
                            className="flex items-center gap-2 px-4 py-2 bg-red-50 text-red-600 border border-red-200 rounded-lg hover:bg-red-100 font-medium text-sm transition-colors disabled:opacity-50"
                        >
                            <XCircle className="w-4 h-4" /> Reject
                        </button>
                        <button
                            disabled={actionLoading}
                            className="flex items-center gap-2 px-4 py-2 bg-slate-100 text-slate-700 border border-slate-200 rounded-lg hover:bg-slate-200 font-medium text-sm transition-colors disabled:opacity-50"
                        >
                            <MessageSquare className="w-4 h-4" /> Request Changes
                        </button>
                        <button
                            onClick={onApprove}
                            disabled={actionLoading}
                            className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 font-medium text-sm shadow-sm transition-colors disabled:opacity-50"
                        >
                            <CheckCircle className="w-4 h-4" /> Approve & Publish
                        </button>
                    </div>
                </div>

                {/* Main Content Area */}
                <div className="flex flex-1 overflow-hidden">
                    {/* Vertical Tabs Sidebar */}
                    <div className="w-64 border-r border-slate-200 bg-slate-50/50 flex-shrink-0 overflow-y-auto">
                        <nav className="p-4 space-y-1">
                            <TabButton
                                active={activeTab === 'details'}
                                onClick={() => setActiveTab('details')}
                                icon={FileText}
                                label="Job Details"
                            />
                            <TabButton
                                active={activeTab === 'company'}
                                onClick={() => setActiveTab('company')}
                                icon={Building2}
                                label="Company Profile"
                            />
                            <TabButton
                                active={activeTab === 'history'}
                                onClick={() => setActiveTab('history')}
                                icon={History}
                                label="Moderation History"
                            />
                            <div className="pt-4 pb-2">
                                <p className="px-3 text-xs font-semibold text-slate-400 uppercase tracking-wider">Advanced (Phase 3)</p>
                            </div>
                            <TabButton
                                active={activeTab === 'ai_analysis'}
                                onClick={() => setActiveTab('ai_analysis')}
                                icon={AlertTriangle}
                                label="AI Analysis"
                                badge="Beta"
                                badgeColor="bg-orange-100 text-orange-700"
                            />
                            <TabButton
                                active={activeTab === 'similar_jobs'}
                                onClick={() => setActiveTab('similar_jobs')}
                                icon={Briefcase}
                                label="Similar Jobs"
                            />
                        </nav>
                    </div>

                    {/* Tab Content */}
                    <div className="flex-1 overflow-y-auto p-6 bg-white">
                        {activeTab === 'details' && <JobDetailsTab job={job} />}
                        {activeTab === 'company' && <CompanyProfileTab employer={job.employer} />}
                        {activeTab === 'history' && <JobHistoryTab jobId={job.id} />}
                        {activeTab === 'ai_analysis' && <AIAnalysisTab job={job} />}
                        {activeTab === 'similar_jobs' && (
                            <div className="flex flex-col items-center justify-center text-slate-500 py-12">
                                <Briefcase className="w-12 h-12 mb-4 text-slate-300" />
                                <h3 className="text-lg font-medium text-slate-900">Similar Jobs Detection</h3>
                                <p className="text-sm mt-1 max-w-sm text-center">This feature will cross-reference this posting with existing active jobs to detect duplicates and spam.</p>
                                <div className="mt-4 px-3 py-1 bg-slate-100 rounded-full text-xs font-semibold uppercase tracking-wider">Coming in Phase 3</div>
                            </div>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}

// Helper specific to this file to avoid massive imports
import { FileText, Building2, History } from "lucide-react";

function TabButton({ active, onClick, icon: Icon, label, badge, badgeColor }: any) {
    return (
        <button
            onClick={onClick}
            className={`w-full flex items-center justify-between gap-3 px-3 py-2.5 rounded-lg text-sm font-medium transition-colors ${active
                ? 'bg-blue-50 text-blue-700'
                : 'text-slate-600 hover:bg-slate-200 hover:text-slate-900'
                }`}
        >
            <div className="flex items-center gap-3">
                <Icon className={`w-4 h-4 ${active ? 'text-blue-600' : 'text-slate-400'}`} />
                {label}
            </div>
            {badge && (
                <span className={`text-[10px] uppercase font-bold px-1.5 py-0.5 rounded-md ${badgeColor || 'bg-slate-200 text-slate-700'}`}>
                    {badge}
                </span>
            )}
        </button>
    );
}
