import { useState } from 'react';
import { XCircle } from 'lucide-react';
import CustomSelect from '../../components/UI/CustomSelect';
import CustomInput from '../../components/UI/CustomInput';
import CustomMultiSelect from '../../components/UI/CustomMultiSelect';

interface NewEnquiryModalProps {
    open: boolean;
    onClose: () => void;
    onSave: (data: EnquiryData) => void;
}

export interface EnquiryData {
    enquiryType: string;
    client: string;
    contact: string;
    course: string[];
    students: number;
    source: string;
    status: string;
}

const NewEnquiryModal = ({ open, onClose, onSave }: NewEnquiryModalProps) => {
    const [formData, setFormData] = useState<EnquiryData>({
        enquiryType: '',
        client: '',
        contact: '',
        course: [],
        students: 120,
        source: '',
        status: 'New',
    });

    // College options
    const collegeOptions = [
        { id: 'fatima-college', name: 'Fatima College' },
        { id: 'psna-college', name: 'PSNA College of Engg' },
        { id: 'kln-college', name: 'K.L.N. College of Engg' },
        { id: 'velammal-engineering', name: 'Velammal Engineering College' },
        { id: 'sethu-institute', name: 'Sethu Institute of Technology' },
        { id: 'kongu-polytechnic', name: 'Kongu Polytechnic College' },
        { id: 'mepco-schlenk', name: 'Mepco Schlenk Engineering College' },
        { id: 'thiyagarajar-college', name: 'Thiyagarajar College of Engineering' },
        { id: 'american-college', name: 'American College' },
        { id: 'lady-doak-college', name: 'Lady Doak College' },
    ];

    // Company options
    const companyOptions = [
        { id: 'zoho-corp', name: 'Zoho Corporation' },
        { id: 'wipro-corp', name: 'Wipro Corporation' },
        { id: 'tcs', name: 'TCS' },
        { id: 'infosys', name: 'Infosys' },
        { id: 'trinity-infosystems', name: 'Trinity Info Systems' },
        { id: 'vantara-softtech', name: 'Vantara Softtech' },
        { id: 'cognizant', name: 'Cognizant' },
        { id: 'hcl-tech', name: 'HCL Technologies' },
        { id: 'tech-mahindra', name: 'Tech Mahindra' },
        { id: 'accenture', name: 'Accenture' },
    ];

    // Course options for multi-select
    const courseOptions = [
        { id: 'python-full-stack', name: 'Python Full Stack' },
        { id: 'java-enterprise', name: 'Java Enterprise' },
        { id: 'data-science-ml', name: 'Data Science & ML' },
        { id: 'cloud-devops', name: 'Cloud & DevOps' },
        { id: 'embedded-c-iot', name: 'Embedded C & IoT' },
        { id: 'soft-skills-aptitude', name: 'Soft Skills & Aptitude' },
        { id: 'java-full-stack', name: 'Java Full Stack' },
        { 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' },
    ];

    const sources = ['College visit', 'Referral', 'Website', 'IndiaMART', 'LinkedIn', 'Repeat client', 'Social Media', 'Email Campaign', 'Walk-in', 'Other'];

    // Status options
    const statusOptions = ['New', 'Qualified', 'Quoted', 'Negotiation', 'Converted', 'Lost'];

    if (!open) return null;

    const handleEnquiryTypeChange = (type: string) => {
        setFormData((prev) => ({
            ...prev,
            enquiryType: type,
            client: '', // Clear client when enquiry type changes
        }));
    };

    // Get client options based on selected enquiry type
    const getClientOptions = () => {
        if (formData.enquiryType === 'College') {
            return collegeOptions.map((opt) => opt.name);
        } else if (formData.enquiryType === 'Company') {
            return companyOptions.map((opt) => opt.name);
        }
        return [];
    };

    const handleSubmit = () => {
        if (!formData.enquiryType) {
            return;
        }

        if (!formData.client.trim()) {
            return;
        }

        if (!formData.contact.trim()) {
            return;
        }

        if (!formData.course.length) {
            return;
        }

        if (!formData.students || formData.students < 1) {
            return;
        }

        if (!formData.source) {
            return;
        }

        if (!formData.status) {
            return;
        }

        onSave(formData);
        resetForm();
    };

    const resetForm = () => {
        setFormData({
            enquiryType: '',
            client: '',
            contact: '',
            course: [],
            students: 120,
            source: '',
            status: 'New',
        });
    };

    const handleClose = () => {
        resetForm();
        onClose();
    };

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

    return (
        <>
            <div className="fixed inset-0 z-50 bg-black/50" onClick={handleClose} />

            <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
                <div className="flex w-full max-w-2xl max-h-[90vh] flex-col overflow-hidden rounded-xl bg-white shadow-2xl" onClick={(e) => e.stopPropagation()}>
                    {/* Header */}
                    <div className="flex shrink-0 items-center justify-between border-b border-gray-200 bg-white px-6 py-4">
                        <h2 className="text-lg font-semibold text-primary">New Enquiry</h2>

                        <button type="button" onClick={handleClose} className="rounded-lg p-1 transition-colors hover:bg-gray-100">
                            <XCircle className="h-5 w-5 text-gray-500" />
                        </button>
                    </div>

                    {/* Form */}
                    <div className="flex-1 overflow-y-auto px-6 py-5">
                        <div className="space-y-5">
                            {/* Row 1: Enquiry Type & Status */}
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {/* Enquiry Type - Radio Buttons */}
                                <div>
                                    <label className="text-[14px] font-semibold text-slate-700">
                                        Enquiry Type
                                        <span className="text-red-600">*</span>
                                    </label>

                                    <div className="mt-2 flex gap-6 text-[13px] font-medium">
                                        <label className="flex cursor-pointer items-center gap-2">
                                            <input
                                                type="radio"
                                                name="enquiryType"
                                                value="College"
                                                checked={formData.enquiryType === 'College'}
                                                onChange={(e) => handleEnquiryTypeChange(e.target.value)}
                                                className="h-4 w-4 border-gray-300 text-secondary focus:ring-secondary/20 focus:ring-2"
                                            />
                                            <span>College</span>
                                        </label>

                                        <label className="flex cursor-pointer items-center gap-2">
                                            <input
                                                type="radio"
                                                name="enquiryType"
                                                value="Company"
                                                checked={formData.enquiryType === 'Company'}
                                                onChange={(e) => handleEnquiryTypeChange(e.target.value)}
                                                className="h-4 w-4 border-gray-300 text-secondary focus:ring-secondary/20 focus:ring-2"
                                            />
                                            <span>Company</span>
                                        </label>
                                    </div>
                                </div>

                                {/* Status */}
                                <CustomSelect
                                    label="Status"
                                    required
                                    value={formData.status}
                                    onChange={(value) =>
                                        setFormData((prev) => ({
                                            ...prev,
                                            status: value,
                                        }))
                                    }
                                    options={statusOptions}
                                    placeholder="Select status"
                                />
                            </div>

                            {/* Row 2: Client / Institution & Source */}
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {/* Client / Institution */}
                                <CustomSelect
                                    label="Client / Institution"
                                    required
                                    value={formData.client}
                                    onChange={(selectedClient) => {
                                        setFormData((prev) => ({
                                            ...prev,
                                            client: selectedClient,
                                        }));
                                    }}
                                    options={getClientOptions()}
                                    placeholder={formData.enquiryType ? 'Select client' : 'Select enquiry type first'}
                                    disabled={!formData.enquiryType}
                                />

                                {/* Source */}
                                <CustomSelect
                                    label="Source"
                                    value={formData.source}
                                    onChange={(value) =>
                                        setFormData((prev) => ({
                                            ...prev,
                                            source: value,
                                        }))
                                    }
                                    options={sources}
                                    placeholder="Select source"
                                />
                            </div>

                            {/* Row 3: Contact Person & Expected Students */}
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {/* Contact Person */}
                                <CustomInput
                                    label="Contact Person"
                                    value={formData.contact}
                                    onChange={(value) =>
                                        setFormData((prev) => ({
                                            ...prev,
                                            contact: value,
                                        }))
                                    }
                                    placeholder="Enter contact person"
                                />

                                {/* Expected Students */}
                                <CustomInput
                                    label="Expected Students"
                                    type="number"
                                    value={formData.students || ''}
                                    onChange={(value) =>
                                        setFormData((prev) => ({
                                            ...prev,
                                            students: parseInt(String(value), 10) || 0,
                                        }))
                                    }
                                    placeholder="Enter expected students"
                                    min={1}
                                />
                            </div>

                            {/* Row 4: Course - Full Width (Multi-select) */}
                            <div>
                                <CustomMultiSelect
                                    label="Course"
                                    value={selectedCourses}
                                    onChange={(selected) => {
                                        setFormData((prev) => ({
                                            ...prev,
                                            course: selected.map((item) => item.id),
                                        }));
                                    }}
                                    options={courseOptions}
                                    placeholder="Select courses..."
                                    required={true}
                                    displayKey="name"
                                    searchKeys={['name']}
                                />
                            </div>

                            {/* Helper text showing selected count */}
                            {formData.course.length > 0 && <div className="text-xs text-gray-500 -mt-2">{formData.course.length} course(s) selected</div>}
                        </div>
                    </div>

                    {/* Footer */}
                    <div className="flex shrink-0 justify-end gap-3 border-t border-gray-200 bg-white px-6 py-4">
                        <button type="button" onClick={handleClose} className="rounded-lg border border-red-400 px-6 py-2.5 font-semibold text-red-600 transition-colors hover:bg-red-50">
                            Cancel
                        </button>

                        <button type="button" onClick={handleSubmit} className="rounded-lg bg-secondary px-6 py-2.5 font-semibold text-white shadow transition-colors hover:bg-secondary/90">
                            Create Enquiry
                        </button>
                    </div>
                </div>
            </div>
        </>
    );
};

export default NewEnquiryModal;
