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: (id: number, data: any) => Promise<boolean>;
    data: any;
}
type OptionType = {
  value: string;
  label: string;
};
const EditLead = ({ open, onClose, onSave, data }: Props) => {
    const [leadSourceOptions, setLeadSourceOptions] = useState<OptionType[]>([]);
    const [assignOptions, setAssignOptions] = useState<OptionType[]>([]);
    const [loading, setLoading] = 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.toString(),
                        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.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]);

    // Helper function to normalize priority - ADD THIS
    const normalizePriority = (value: any): string => {
        if (!value) return 'medium';

        // Convert to string and lowercase
        const strValue = String(value).toLowerCase().trim();

        // Map various possible values to valid ones
        const priorityMap: { [key: string]: string } = {
            'low': 'low',
            'medium': 'medium',
            'high': 'high',
            'l': 'low',
            'm': 'medium',
            'h': 'high',
            '0': 'low',
            '1': 'medium',
            '2': 'high',
        };

        return priorityMap[strValue] || 'medium';
    };

    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_priority must be one of the following values: low, medium, high'),
        lead_source_id: Yup.string()
            .required("Lead source is required"),
        assign_to: Yup.string()
            .nullable(),
    });

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: {
            lead_name: data?.lead_name || data?.name || "",
            lead_email: data?.lead_email || data?.email || "",
            lead_mobile: data?.lead_mobile || data?.phone || "",
            lead_value: data?.lead_value || data?.potentialValue || "",
            lead_priority: normalizePriority(data?.lead_priority || data?.priority), // FIXED HERE
            lead_source_id: data?.lead_source_id?.toString() || data?.leadSource?.id?.toString() || "",
            assign_to: data?.assign_to?.toString() || data?.assign_staff?.id?.toString() || "",
        },
        validationSchema,
        onSubmit: async (values, { setSubmitting }) => {
            setSubmitting(true);
            try {
                // Convert string IDs back to numbers for API
                const submitValues = {
                    ...values,
                    lead_source_id: values.lead_source_id ? parseInt(values.lead_source_id) : null,
                    assign_to: values.assign_to ? parseInt(values.assign_to) : null,
                    lead_value: values.lead_value ? Number(values.lead_value) : null,
                };
                const success = await onSave(data?.id, submitValues);
                if (success) {
                    onClose();
                }
            } catch (error) {
                console.error('Error updating lead:', error);
            } finally {
                setSubmitting(false);
            }
        },
    });

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

    // Debug effect to check priority value
    useEffect(() => {
        if (open) {
            console.log('=== Priority Debug ===');
            console.log('Original data.lead_priority:', data?.lead_priority);
            console.log('Original data.priority:', data?.priority);
            console.log('Normalized priority value:', formik.values.lead_priority);
            console.log('Priority options:', priorityOptions);
            console.log('Formik errors:', formik.errors);
        }
    }, [open, data, formik.values.lead_priority, formik.errors]);

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Update 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 ? "Updating..." : "Update Lead"}
                    </button>
                </>
            }
        >
            <form className="space-y-4">
                <div>
                    <label className="text-md text-gray-900">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-md text-gray-900">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-md text-gray-900">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-md text-gray-900">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-md text-gray-900">Priority <span className="text-danger">*</span></label>
                        <Select
                            options={priorityOptions}
                            value={priorityOptions.find(o => o.value === formik.values.lead_priority)}
                            onChange={(val: any) => {
                              // Ensure we're setting exactly 'low', 'medium', or 'high'
                                const selectedValue = val?.value;
                                if (selectedValue && ['low', 'medium', 'high'].includes(selectedValue)) {
                                    formik.setFieldValue("lead_priority", selectedValue);
                                    setTimeout(() => {
                                        formik.setFieldTouched("lead_priority", true);
                                        formik.validateField("lead_priority");
                                    }, 0);
                                }
                            }}
                            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-md text-gray-900">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-md text-gray-900">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>

                {/* Current Status Display (Read-only) */}
                {data?.status !== undefined && (
                    <div className="bg-gray-50 p-3 rounded-lg">
                        <label className="text-md text-gray-900">Current Status</label>
                        <p className="text-sm font-medium mt-1">
                            {data.status === 0 && "New"}
                            {data.status === 1 && "Inactive"}
                            {data.status === 3 && "Contacted"}
                            {data.status === 4 && "Interested"}
                            {data.status === 5 && "Converted"}
                            {data.status === 6 && "Follow-up"}
                            {data.status === 7 && "Lost"}
                        </p>
                    </div>
                )}
            </form>
        </Modal>
    );
};

export default EditLead;
