import { useFormik } from 'formik';
import * as Yup from 'yup';
import Modal from '../../components/Modals';
import FileDropzone from '../../components/FileDropzone';
import Select from '../../components/Select';
import IconDownload from '../../components/Icon/IconDownload';
import api from '../../api/axios';
import { useEffect, useState } from 'react';
import { toast } from 'react-toastify';

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (data: any) => Promise<boolean>;
}
type OptionType = {
  value: string;
  label: string;
};
const BulkUpload = ({ open, onClose, onSave }: Props) => {
    const [leadSourceOptions, setLeadSourceOptions] = useState<OptionType[]>([]);
    const [staffOptions, setStaffOptions] = useState<OptionType[]>([]);
    const [uploading, setUploading] = useState(false);

    // Fetch lead sources
    useEffect(() => {
        const fetchSources = async () => {
            try {
                const response = await api.get('/source/list');
                if (response.data.status === 200) {
                    const options = response.data.data.map((source: any) => ({
                        value: source.id,
                        label: source.name
                    }));
                    setLeadSourceOptions(options);
                }
            } catch (error) {
                console.error('Error fetching lead sources:', error);
                toast.error('Failed to load lead sources');
            }
        };

        if (open) {
            fetchSources();
        }
    }, [open]);

    // Fetch staff list
    useEffect(() => {
        const fetchStaff = async () => {
            try {
                const response = await api.get('/staff/lists');
                if (response.data.status === 200) {
                    const options = response.data.data.map((staff: any) => ({
                        value: staff.id,
                        label: staff.staff_name
                    }));
                    setStaffOptions(options);
                }
            } catch (error) {
                console.error('Error fetching staff:', error);
                toast.error('Failed to load staff list');
            }
        };

        if (open) {
            fetchStaff();
        }
    }, [open]);

    const validationSchema = Yup.object({
        lead_source_id: Yup.number().required('Lead source is required'),
        assign_to: Yup.number().nullable(),
        file: Yup.mixed().required('File is required'),
    });

    const formik = useFormik({
        initialValues: {
            lead_source_id: '',
            assign_to: '',
            file: null as File | null,
        },
        validationSchema,
        onSubmit: async (values, { setSubmitting, resetForm }) => {
            setUploading(true);
            try {
                const formData = new FormData();
                formData.append('lead_source_id', String(values.lead_source_id));
                if (values.assign_to) {
                    formData.append('assign_to', String(values.assign_to));
                }
                if (values.file) {
                    formData.append('file', values.file);
                }

                const response = await api.post('/lead/bulk-upload', formData, {
                    headers: { 'Content-Type': 'multipart/form-data' }
                });

                if (response.data.status === true) {
                    toast.success(response.data.message || 'Bulk upload successful');
                    resetForm();
                    onClose();
                    if (onSave) {
                        await onSave(response.data);
                    }
                }
            } catch (error: any) {
                console.error('Error uploading file:', error);
                const errorMsg = error.response?.data?.message || 'Failed to upload leads';
                toast.error(errorMsg);
            } finally {
                setUploading(false);
                setSubmitting(false);
            }
        },
    });

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Bulk Upload Leads"
            maxWidth="max-w-md"
            footer={
                <>
                    <button
                        onClick={onClose}
                        className="btn btn-outline-danger"
                        disabled={uploading}
                    >
                        Cancel
                    </button>
                    <button
                        onClick={() => formik.handleSubmit()}
                        className="btn btn-primary"
                        disabled={uploading || !formik.isValid}
                    >
                        {uploading ? "Uploading..." : "Upload Leads"}
                    </button>
                </>
            }
        >
            <div className="space-y-4">
                {/* Sample Download */}
                <div className="flex justify-end">
                    <a
                        href="/samples/Lead_Bulk_Upload.xlsx"
                        download
                        className="flex items-center gap-2 text-sm text-rose-600 hover:underline"
                    >
                        <IconDownload className="w-4 h-4" />
                        Download Sample Excel
                    </a>
                </div>

                <div>
                    <label className="block mb-1 font-medium text-sm">Lead Source <span className='text-danger'>*</span></label>
                    <Select
                        options={leadSourceOptions}
                        value={leadSourceOptions.find(opt => opt.value === formik.values.lead_source_id)}
                         onChange={(val: any) => {
                            formik.setFieldValue("lead_source_id", val?.value || "");

                            setTimeout(() => {
                                formik.setFieldTouched("lead_source_id", true);
                                formik.validateField("lead_source_id");
                            }, 0);
                        }}
                        placeholder="Select lead source"
                    />
                    {formik.touched.lead_source_id && formik.errors.lead_source_id && (
                        <p className="text-red-500 text-xs mt-1">
                            {formik.errors.lead_source_id as string}
                        </p>
                    )}
                </div>

                <div>
                    <label className="block mb-1 font-medium text-sm">Assign Staff <span className='text-danger'>*</span></label>
                    <Select
                        options={staffOptions}
                        value={staffOptions.find(opt => opt.value === formik.values.assign_to)}
                         onChange={(val: any) => {
                            formik.setFieldValue("assign_to", val?.value || "");

                            setTimeout(() => {
                                formik.setFieldTouched("assign_to", true);
                                formik.validateField("assign_to");
                            }, 0);
                        }}
                        placeholder="Select staff"
                        isClearable
                        isLoading={staffOptions.length === 0}
                    />
                    {formik.touched.assign_to && formik.errors.assign_to && (
                        <p className="text-red-500 text-xs mt-1">
                            {formik.errors.assign_to as string}
                        </p>
                    )}
                </div>

                <div>
                    <label className="block mb-2 font-medium text-sm">Upload Excel File *</label>
                    <FileDropzone
                        value={formik.values.file}
                        onChange={(file) => {
                            formik.setFieldValue('file', file);
                            formik.setFieldTouched('file', true);
                        }}
                        accept=".xlsx,.xls,.csv"
                        maxSize={5 * 1024 * 1024} // 5MB
                    />
                    {formik.touched.file && formik.errors.file && (
                        <p className="text-red-500 text-sm mt-1">
                            {formik.errors.file as string}
                        </p>
                    )}
                    <p className="text-xs text-gray-500 mt-2">
                        Accepted formats: .xlsx, .xls, .csv (Max 5MB)
                    </p>
                </div>

                {/* Instructions */}
                <div className="bg-blue-50 p-3 rounded-lg mt-4">
                    <p className="text-xs text-blue-800 font-medium mb-1">Instructions:</p>
                    <ul className="text-xs text-blue-700 space-y-1 list-disc pl-4">
                        <li>Download the sample file for correct format</li>
                        <li>Required columns: Name, Mobile (options) Email, Priority</li>
                        <li>Priority values: low, medium, high</li>
                        <li>Do not modify the column headers</li>
                    </ul>
                </div>
            </div>
        </Modal>
    );
};

export default BulkUpload;
