import { useState } from 'react';
import { X, Calendar, Building2, Users, Clock, FileText, Briefcase, GraduationCap, BookOpen } from 'lucide-react';
import CustomSelect from '../../components/UI/CustomSelect';
import CustomInput from '../../components/UI/CustomInput';
import CustomMultiSelect from '../../components/UI/CustomMultiSelect';
import DatePicker from 'react-datepicker';
import 'react-datepicker/dist/react-datepicker.css';

type EnquiryType = 'College' | 'Corporate';

interface Enquiry {
    id: string;
    date: string;
    client: string;
    contact: string;
    course: string;
    students: number;
    source: string;
    status: string;
    type: EnquiryType;
}

interface AddRequirementModalProps {
    open: boolean;
    onClose: () => void;
    enquiry: Enquiry | null;
}

interface RequirementData {
    degree: string[];
    course: string[];
    topics: string;
    trainingHours: number;
    batchCount: number;
    studentsPerBatch: number;
    startDate: string;
    endDate: string;
    clientExpectations: string;
    projectRequirement: string;
    assessmentRequired: string;
    certificationRequired: string;
    remarks: string;

    // Corporate fields
    industry: string;
    department: string;
}

export default function AddRequirementModal({ open, onClose, enquiry }: AddRequirementModalProps) {
    const degreeOptions = [
        { id: 'be-btech', name: 'B.E / B.Tech' },
        { id: 'bsc', name: 'B.Sc' },
        { id: 'bca', name: 'BCA' },
        { id: 'mca', name: 'MCA' },
        { id: 'mba', name: 'MBA' },
        { id: 'me-mtech', name: 'M.E / M.Tech' },
        { id: 'msc', name: 'M.Sc' },
        { id: 'other', name: 'Other' },
    ];

    const courseOptions = [
        { id: 'python-full-stack', name: 'Python Full Stack' },
        { id: 'java-full-stack', name: 'Java Full Stack' },
        { id: 'data-science-ml', name: 'Data Science & ML' },
        { id: 'embedded-c-iot', name: 'Embedded C & IoT' },
        { id: 'cloud-devops', name: 'Cloud & DevOps' },
        { id: 'soft-skills-aptitude', name: 'Soft Skills & Aptitude' },
        { id: 'mern-stack', name: 'MERN Stack' },
        { id: 'mean-stack', name: 'MEAN Stack' },
        { id: 'blockchain-dev', name: 'Blockchain Development' },
        { id: 'cybersecurity', name: 'Cybersecurity' },
        { id: 'ui-ux-design', name: 'UI/UX Design' },
        { id: 'leadership-training', name: 'Leadership Training' },
        { id: 'communication-skills', name: 'Communication Skills' },
        { id: 'ai-ml', name: 'AI & Machine Learning' },
        { id: 'other', name: 'Other' },
    ];

    const [formData, setFormData] = useState<RequirementData>({
        degree: [],
        course: enquiry?.course ? [enquiry.course] : [],
        topics: '',
        trainingHours: 2,
        batchCount: 2,
        studentsPerBatch: enquiry?.students || 40,
        startDate: '',
        endDate: '',
        clientExpectations: '',
        projectRequirement: '',
        assessmentRequired: '',
        certificationRequired: '',
        remarks: '',

        // Corporate
        industry: '',
        department: '',
    });

    const handleChange = (field: keyof RequirementData, value: string | number | string[]) => {
        setFormData((prev) => ({
            ...prev,
            [field]: value,
        }));
    };

    // Convert string date to Date object for DatePicker
    const getDateValue = (dateString: string): Date | null => {
        if (!dateString) return null;
        try {
            const parts = dateString.split('-');
            if (parts.length === 3) {
                return new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]));
            }
            return null;
        } catch {
            return null;
        }
    };

    // Handle date change from DatePicker
    const handleDateChange = (field: 'startDate' | 'endDate', date: Date | null) => {
        if (date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            handleChange(field, `${year}-${month}-${day}`);
        } else {
            handleChange(field, '');
        }
    };

    const handleSubmit = () => {
        console.log('Form submitted:', formData);
        onClose();
    };

    // Get selected courses for multi-select
    const selectedCourses = courseOptions.filter((course) => formData.course.includes(course.id));

    if (!open) return null;

    return (
        <>
            <div className="fixed inset-0 bg-black/50 z-[100]" onClick={onClose} />
            <div className="fixed inset-0 z-[100] flex items-center justify-center pointer-events-none px-4">
                <div className="pointer-events-auto bg-white rounded-xl shadow-2xl w-full max-w-2xl mx-4 max-h-[95vh] overflow-y-auto">
                    {/* Modal Header */}
                    <div className="flex items-center justify-between px-6 py-4 border-b border-gray-200 sticky top-0 bg-white z-10">
                        <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
                                <Briefcase className="w-5 h-5 text-primary" />
                            </div>
                            <div>
                                <h2 className="text-lg font-semibold text-primary">Add Requirement</h2>
                                {enquiry && (
                                    <p className="text-xs text-gray-500">
                                        For: {enquiry.client} · {enquiry.id}
                                    </p>
                                )}
                            </div>
                        </div>
                        <button onClick={onClose} className="p-1 hover:bg-gray-100 rounded-lg transition-colors">
                            <X className="w-5 h-5 text-gray-500" />
                        </button>
                    </div>

                    {/* Modal Body */}
                    <div className="px-6 py-4">
                        {/* Selected Client Details */}
                        {enquiry && (
                            <div className="mb-5 rounded-lg border border-gray-200 bg-gray-50 p-4">
                                <div className="flex items-center justify-between mb-3">
                                    <h3 className="text-sm font-semibold text-primary flex items-center gap-2">
                                        <Building2 className="w-4 h-4" />
                                        Client Details
                                    </h3>
                                    <span
                                        className={`rounded-full px-2.5 py-1 text-xs font-medium ${
                                            enquiry.type === 'College' ? 'bg-blue-50 text-blue-700 border border-blue-200' : 'bg-purple-50 text-purple-700 border border-purple-200'
                                        }`}
                                    >
                                        {enquiry.type}
                                    </span>
                                </div>

                                <div className="grid grid-cols-2 gap-3">
                                    <div>
                                        <p className="text-xs text-gray-500">Client</p>
                                        <p className="text-sm font-medium text-gray-900">{enquiry.client}</p>
                                    </div>
                                    <div>
                                        <p className="text-xs text-gray-500">Contact</p>
                                        <p className="text-sm font-medium text-gray-900">{enquiry.contact}</p>
                                    </div>
                                    <div>
                                        <p className="text-xs text-gray-500">Course</p>
                                        <p className="text-sm font-medium text-gray-900">{enquiry.course}</p>
                                    </div>
                                    <div>
                                        <p className="text-xs text-gray-500">Students</p>
                                        <p className="text-sm font-medium text-gray-900">{enquiry.students}</p>
                                    </div>
                                </div>
                            </div>
                        )}

                        <div className="space-y-4">
                            {enquiry?.type === 'College' && (
                                <>
                                    {/* Degree & Course */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <CustomMultiSelect
                                                label="Degree"
                                                required
                                                options={degreeOptions}
                                                value={degreeOptions.filter((option) => formData.degree.includes(option.id))}
                                                onChange={(value) => {
                                                    handleChange(
                                                        'degree',
                                                        value.map((option) => option.id),
                                                    );
                                                }}
                                                placeholder="Select Degree"
                                                icon={<GraduationCap className="w-4 h-4 text-gray-400" />}
                                            />
                                        </div>
                                        <div>
                                            <CustomMultiSelect
                                                label="Course"
                                                required
                                                value={selectedCourses}
                                                onChange={(selected) => {
                                                    handleChange(
                                                        'course',
                                                        selected.map((item) => item.id),
                                                    );
                                                }}
                                                options={courseOptions}
                                                placeholder="Select courses..."
                                                displayKey="name"
                                                searchKeys={['name']}
                                                icon={<BookOpen className="w-4 h-4 text-gray-400" />}
                                            />
                                        </div>
                                    </div>

                                    {/* Batch Count & Training Hours */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <CustomInput
                                            label="Batch Count"
                                            required
                                            type="number"
                                            value={formData.batchCount}
                                            onChange={(value) => handleChange('batchCount', Number(value))}
                                            placeholder="Enter batch count"
                                            min={1}
                                            icon={<Users className="w-4 h-4" />}
                                        />
                                        <CustomInput
                                            label="Hours"
                                            required
                                            type="number"
                                            value={formData.trainingHours}
                                            onChange={(value) => handleChange('trainingHours', Number(value))}
                                            placeholder="Enter training hours"
                                            min={1}
                                            icon={<Clock className="w-4 h-4" />}
                                        />
                                    </div>

                                    {/* Start Date & End Date */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <label className="text-sm font-medium text-gray-700 block mb-1.5">Preferred Start Date</label>
                                            <div className="relative">
                                                <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 z-10 pointer-events-none" />
                                                <DatePicker
                                                    selected={getDateValue(formData.startDate)}
                                                    onChange={(date: Date | null) => handleDateChange('startDate', date)}
                                                    dateFormat="dd-MM-yyyy"
                                                    placeholderText="Select Start Date"
                                                    isClearable
                                                    className="
                                                        w-full pl-9 pr-4 py-2
                                                        border border-gray-200
                                                        rounded-lg text-sm text-gray-700
                                                        bg-white
                                                        focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20
                                                        cursor-pointer
                                                    "
                                                    popperClassName="financial-year-datepicker"
                                                    showPopperArrow={false}
                                                    calendarClassName="border border-gray-200 rounded-lg shadow-lg"
                                                />
                                            </div>
                                        </div>
                                        <div>
                                            <label className="text-sm font-medium text-gray-700 block mb-1.5">Preferred End Date</label>
                                            <div className="relative">
                                                <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 z-10 pointer-events-none" />
                                                <DatePicker
                                                    selected={getDateValue(formData.endDate)}
                                                    onChange={(date: Date | null) => handleDateChange('endDate', date)}
                                                    dateFormat="dd-MM-yyyy"
                                                    placeholderText="Select End Date"
                                                    isClearable
                                                    className="
                                                        w-full pl-9 pr-4 py-2
                                                        border border-gray-200
                                                        rounded-lg text-sm text-gray-700
                                                        bg-white
                                                        focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20
                                                        cursor-pointer
                                                    "
                                                    popperClassName="financial-year-datepicker"
                                                    showPopperArrow={false}
                                                    calendarClassName="border border-gray-200 rounded-lg shadow-lg"
                                                />
                                            </div>
                                        </div>
                                    </div>

                                    {/* Description - Textarea */}
                                    <div>
                                        <CustomInput
                                            label="Description"
                                            type="textarea"
                                            value={formData.clientExpectations}
                                            onChange={(value) => handleChange('clientExpectations', value)}
                                            placeholder="Enter your description"
                                            rows={4}
                                            icon={<FileText className="w-4 h-4" />}
                                        />
                                    </div>
                                </>
                            )}

                            {enquiry?.type === 'Corporate' && (
                                <>
                                    {/* Industry & Department */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <CustomSelect
                                            label="Industry"
                                            required
                                            value={formData.industry}
                                            onChange={(value) => handleChange('industry', value)}
                                            options={[
                                                'Information Technology (IT)',
                                                'Banking & Financial Services',
                                                'Automotive',
                                                'Manufacturing',
                                                'Healthcare & Pharmaceuticals',
                                                'Telecommunications',
                                                'Retail & E-commerce',
                                                'Consulting & Professional Services',
                                                'BPO & KPO',
                                                'Other',
                                            ]}
                                            placeholder="Select Industry"
                                            icon={<Building2 className="w-4 h-4" />}
                                        />
                                        <CustomInput
                                            label="Department"
                                            required
                                            value={formData.department}
                                            onChange={(value) => handleChange('department', value)}
                                            placeholder="Enter department"
                                            icon={<Briefcase className="w-4 h-4" />}
                                        />
                                    </div>

                                    {/* Course - Multi-select & Training Hours */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <CustomMultiSelect
                                                label="Training Course"
                                                required
                                                value={selectedCourses}
                                                onChange={(selected) => {
                                                    handleChange(
                                                        'course',
                                                        selected.map((item) => item.id),
                                                    );
                                                }}
                                                options={courseOptions}
                                                placeholder="Select courses..."
                                                displayKey="name"
                                                searchKeys={['name']}
                                                icon={<BookOpen className="w-4 h-4 text-gray-400" />}
                                            />
                                        </div>
                                        <CustomInput
                                            label="Training Hours"
                                            required
                                            type="number"
                                            value={formData.trainingHours}
                                            onChange={(value) => handleChange('trainingHours', Number(value))}
                                            placeholder="Enter training hours"
                                            min={1}
                                            icon={<Clock className="w-4 h-4" />}
                                        />
                                    </div>

                                    {/* Batch Count & Employees/Batch */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <CustomInput
                                            label="Batch Count"
                                            required
                                            type="number"
                                            value={formData.batchCount}
                                            onChange={(value) => handleChange('batchCount', Number(value))}
                                            placeholder="Enter batch count"
                                            min={1}
                                            icon={<Users className="w-4 h-4" />}
                                        />
                                        <CustomInput
                                            label="Employees / Batch"
                                            required
                                            type="number"
                                            value={formData.studentsPerBatch}
                                            onChange={(value) => handleChange('studentsPerBatch', Number(value))}
                                            placeholder="Enter employees per batch"
                                            min={1}
                                            icon={<Users className="w-4 h-4" />}
                                        />
                                    </div>

                                    {/* Start Date & End Date */}
                                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                        <div>
                                            <label className="text-sm font-medium text-gray-700 block mb-1.5">Preferred Start Date</label>
                                            <div className="relative">
                                                <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 z-10 pointer-events-none" />
                                                <DatePicker
                                                    selected={getDateValue(formData.startDate)}
                                                    onChange={(date: Date | null) => handleDateChange('startDate', date)}
                                                    dateFormat="dd-MM-yyyy"
                                                    placeholderText="Select Start Date"
                                                    isClearable
                                                    className="
                                                        w-full pl-9 pr-4 py-2
                                                        border border-gray-200
                                                        rounded-lg text-sm text-gray-700
                                                        bg-white
                                                        focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20
                                                        cursor-pointer
                                                    "
                                                    popperClassName="financial-year-datepicker"
                                                    showPopperArrow={false}
                                                    calendarClassName="border border-gray-200 rounded-lg shadow-lg"
                                                />
                                            </div>
                                        </div>
                                        <div>
                                            <label className="text-sm font-medium text-gray-700 block mb-1.5">Preferred End Date</label>
                                            <div className="relative">
                                                <Calendar className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400 z-10 pointer-events-none" />
                                                <DatePicker
                                                    selected={getDateValue(formData.endDate)}
                                                    onChange={(date: Date | null) => handleDateChange('endDate', date)}
                                                    dateFormat="dd-MM-yyyy"
                                                    placeholderText="Select End Date"
                                                    isClearable
                                                    className="
                                                        w-full pl-9 pr-4 py-2
                                                        border border-gray-200
                                                        rounded-lg text-sm text-gray-700
                                                        bg-white
                                                        focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20
                                                        cursor-pointer
                                                    "
                                                    popperClassName="financial-year-datepicker"
                                                    showPopperArrow={false}
                                                    calendarClassName="border border-gray-200 rounded-lg shadow-lg"
                                                />
                                            </div>
                                        </div>
                                    </div>

                                    {/* Client Expectations - Textarea */}
                                    <div>
                                        <CustomInput
                                            label="Client Expectations"
                                            type="textarea"
                                            value={formData.clientExpectations}
                                            onChange={(value) => handleChange('clientExpectations', value)}
                                            placeholder="Enter client expectations"
                                            rows={4}
                                            icon={<FileText className="w-4 h-4" />}
                                        />
                                    </div>
                                </>
                            )}
                        </div>
                    </div>

                    {/* Modal Footer */}
                    <div className="flex items-center justify-end gap-3 px-6 py-4 border-t border-gray-200 sticky bottom-0 bg-white">
                        <button type="button" onClick={onClose} className="px-6 py-2.5 rounded-lg border border-red-400 text-red-600 font-semibold hover:bg-red-50 transition-colors">
                            Cancel
                        </button>
                        <button type="button" onClick={handleSubmit} className="px-6 py-2.5 rounded-lg bg-secondary text-white font-semibold shadow hover:bg-secondary/90 transition-colors">
                            Add Requirement
                        </button>
                    </div>
                </div>
            </div>
        </>
    );
}
