import { useFormik } from "formik";
import * as Yup from "yup";
import Modal from "../../components/Modals";
import Select from "../../components/Select";
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 AddLead = ({ open, onClose, onSave }: Props) => {
    const [leadSourceOptions, setLeadSourceOptions] = useState<OptionType[]>([]);
    const [assignOptions, setAssignOptions] = useState<OptionType[]>([]);
    const [loading, setLoading] = useState(false);

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

        if (open) {
            fetchSource();
        }
    }, [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.toString(),
                        label: staff.staff_name
                    }));
                    setAssignOptions(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_name: Yup.string()
            .required("Name is required")
            .min(2, "Name must be at least 2 characters"),
        lead_email: Yup.string()
            .email("Invalid email format")
            .nullable(),
        lead_mobile: Yup.string()
            .required("Phone number is required")
            .min(10, "Phone number must be at least 10 digits"),
        lead_value: Yup.number()
            .min(0, "Lead value must be positive")
            .nullable(),
        lead_priority: Yup.string()
            .required("Priority is required")
            .oneOf(['low', 'medium', 'high']),
        lead_source_id: Yup.string()
            .required("Lead source is required"),
        assign_to: Yup.string()
            .nullable(),
    });

    const formik = useFormik({
        initialValues: {
            lead_name: "",
            lead_email: "",
            lead_source_id: "",
            lead_mobile: "",
            lead_value: "",
            lead_priority: "",
            assign_to: "",
        },
        validationSchema,
        onSubmit: async (values, { setSubmitting, resetForm }) => {
            setSubmitting(true);
            try {
                const success = await onSave(values);
                if (success) {
                    resetForm();
                    onClose();
                }
            } catch (error) {
                console.error('Error saving lead:', error);
            } finally {
                setSubmitting(false);
            }
        },
    });

    const priorityOptions = [
        { value: "low", label: "Low" },
        { value: "medium", label: "Medium" },
        { value: "high", label: "High" },
    ];

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Add New Lead"
            maxWidth="max-w-md"
            footer={
                <>
                    <button
                        onClick={onClose}
                        className="btn btn-outline-danger"
                        type="button"
                        disabled={formik.isSubmitting}
                    >
                        Cancel
                    </button>
                    <button
                        onClick={() => formik.handleSubmit()}
                        className="btn btn-primary"
                        type="button"
                        disabled={formik.isSubmitting}
                    >
                        {formik.isSubmitting ? "Creating..." : "Create Lead"}
                    </button>
                </>
            }
        >
            <form className="space-y-4">
                <div>
                    <label className="text-xs text-gray-500">Full Name <span className='text-danger'>*</span></label>
                    <input
                        name="lead_name"
                        placeholder="John Doe"
                        className="form-input w-full mt-1"
                        value={formik.values.lead_name}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                    />
                    {formik.touched.lead_name && formik.errors.lead_name && (
                        <p className="text-red-500 text-xs mt-1">{formik.errors.lead_name as string}</p>
                    )}
                </div>

                <div className="grid grid-cols-2 gap-3">
                    <div>
                        <label className="text-xs text-gray-500">Email</label>
                        <input
                            name="lead_email"
                            type="email"
                            placeholder="john@example.com"
                            className="form-input w-full mt-1"
                            value={formik.values.lead_email}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                        />
                        {formik.touched.lead_email && formik.errors.lead_email && (
                            <p className="text-red-500 text-xs mt-1">{formik.errors.lead_email as string}</p>
                        )}
                    </div>
                    <div>
                        <label className="text-xs text-gray-500">Phone <span className='text-danger'>*</span></label>
                        <input
                            name="lead_mobile"
                            placeholder="9876543210"
                            className="form-input w-full mt-1"
                            value={formik.values.lead_mobile}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                        />
                        {formik.touched.lead_mobile && formik.errors.lead_mobile && (
                            <p className="text-red-500 text-xs mt-1">{formik.errors.lead_mobile as string}</p>
                        )}
                    </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                    <div>
                        <label className="text-xs text-gray-500">Lead Value (₹)</label>
                        <input
                            name="lead_value"
                            type="number"
                            placeholder="15000"
                            className="form-input w-full mt-1"
                            value={formik.values.lead_value}
                            onChange={formik.handleChange}
                            onBlur={formik.handleBlur}
                        />
                        {formik.touched.lead_value && formik.errors.lead_value && (
                            <p className="text-red-500 text-xs mt-1">{formik.errors.lead_value as string}</p>
                        )}
                    </div>
                    <div>
                        <label className="text-xs text-gray-500">Priority <span className='text-danger'>*</span></label>
                        <Select
                            options={priorityOptions}
                            value={priorityOptions.find(o => o.value === formik.values.lead_priority)}
                            onChange={(val: any) => {
                                formik.setFieldValue("lead_priority", val?.value || "");
                                formik.setFieldTouched("lead_priority", true);
                            }}
                            placeholder="Select priority"
                        />
                        {formik.touched.lead_priority && formik.errors.lead_priority && (
                            <p className="text-red-500 text-xs mt-1">{formik.errors.lead_priority as string}</p>
                        )}
                    </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                    <div>
                        <label className="text-xs text-gray-500">Lead Source <span className='text-danger'>*</span></label>
                        <Select
                            options={leadSourceOptions}
                            value={leadSourceOptions.find(o => o.value === formik.values.lead_source_id)}
                            onChange={(val: any) => {
                                formik.setFieldValue("lead_source_id", val?.value || "");
                                formik.setFieldTouched("lead_source_id", true);
                            }}
                            placeholder="Select source"
                            isLoading={leadSourceOptions.length === 0}
                        />
                        {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="text-xs text-gray-500">Assign To</label>
                        <Select
                            options={assignOptions}
                            value={assignOptions.find(o => o.value === formik.values.assign_to)}
                            onChange={(val: any) => {
                                formik.setFieldValue("assign_to", val?.value || "");
                                formik.setFieldTouched("assign_to", true);
                            }}
                            placeholder="Select staff"
                            isClearable
                            isLoading={assignOptions.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>
            </form>
        </Modal>
    );
};

export default AddLead;
