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

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (status: string, data?: any) => Promise<boolean>;
    data?: {
        id: number;
        title: string;
        lead?: {
            id: number;
            lead_name: string;
            lead_mobile: string;
            lead_email: string;
        };
        status: string;
        mode: string;
        priority: string;
        reminder_date: string;
        reminder_time: string;
        assign_to: number | null;
    } | null;
}

const UpdateStatus = ({ open, onClose, onSave, data }: Props) => {
    const [scheduleNext, setScheduleNext] = useState(false);
    const [updating, setUpdating] = useState(false);

    // Validation schema based on schedule next option
    const getValidationSchema = () => {
        const baseSchema = {
            outcomes: Yup.string().required("Outcome is required"),
            comments: Yup.string().nullable(),
        };

        if (scheduleNext) {
            return Yup.object({
                ...baseSchema,
                next_title: Yup.string().required("Next follow-up title is required"),
                next_mode: Yup.string().required("Mode is required"),
                next_priority: Yup.string().required("Priority is required"),
                next_description: Yup.string().nullable(),
                next_date_time: Yup.string().required("Due date & time is required"),
            });
        }

        return Yup.object(baseSchema);
    };

    // Formik
    const formik = useFormik({
        initialValues: {
            outcomes: "",
            comments: "",
            next_title: "",
            next_mode: "",
            next_priority: "medium",
            next_description: "",
            next_date_time: "",
        },
        validationSchema: getValidationSchema(),
        onSubmit: async (values) => {
            setUpdating(true);
            try {
                // Prepare update data for current reminder
                const updateData: any = {
                    status: 'completed',
                    outcomes: values.outcomes,
                    comments: values.comments,
                };

                // Add schedule next data if applicable
                if (scheduleNext) {
                    updateData.schedule_next = true;
                    updateData.next_title = values.next_title;
                    updateData.next_mode = values.next_mode;
                    updateData.next_priority = values.next_priority;
                    updateData.next_description = values.next_description;
                    updateData.next_date_time = values.next_date_time;
                    updateData.next_assign_to = data?.assign_to || null;
                }

                const response = await api.put(`/reminder/status/${data?.id}`, updateData);

                if (response.data.status === true) {
                    if (scheduleNext && response.data.data.next_reminder) {
                        toast.success('Reminder completed and next follow-up scheduled');
                    } else {
                        toast.success('Reminder marked as completed');
                    }

                    await onSave('completed', scheduleNext ? values : null);
                    handleClose();
                }
            } catch (error: any) {
                console.error('Error updating status:', error);
                const errorMsg = error.response?.data?.message || 'Failed to update status';
                toast.error(errorMsg);

                // Display validation errors if any
                if (error.response?.data?.errors) {
                    const errors = error.response.data.errors;
                    Object.keys(errors).forEach(key => {
                        toast.error(`${key}: ${errors[key][0]}`);
                    });
                }
            } finally {
                setUpdating(false);
            }
        },
    });

    const handleClose = () => {
        formik.resetForm();
        setScheduleNext(false);
        onClose();
    };
    // const outcomesOptions = [
    //     { value: "Connected - Interested", label: "Connected - Interested" },
    //     { value: "Connected - Not Interested", label: "Connected - Not Interested" },
    //     { value: "Connected - Call Back Later", label: "Connected - Call Back Later" },
    //     { value: "Not Connected - Busy", label: "Not Connected - Busy" },
    //     { value: "Not Connected - Wrong Number", label: "Not Connected - Wrong Number" },
    //     { value: "Not Connected - No Answer", label: "Not Connected - No Answer" },
    //     { value: "Follow-up Required", label: "Follow-up Required" },
    //     { value: "Converted to Student", label: "Converted to Student" },
    // ];
     const outcomesOptions = [
        { value: "Low", label: "Low" },
        { value: "Medium", label: "Medium" },
        { value: "High", label: "High" },
    ];
    const modeOption = [
        { value: "Call", label: "Call" },
        { value: "WhatsApp", label: "WhatsApp" },
        { value: "Visit", label: "Visit" },
        { value: "Email", label: "Email" },
    ];

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

    // Reset form when modal opens
    useEffect(() => {
        if (!open) {
            formik.resetForm();
            setScheduleNext(false);
        }
    }, [open]);

    if (!data) return null;

    return (
        <Modal
            open={open}
            onClose={handleClose}
            title="Update Reminder Status"
            maxWidth="max-w-xl"
            footer={
                <>
                    <button
                        onClick={handleClose}
                        className="btn btn-outline-danger"
                        type="button"
                        disabled={updating}
                    >
                        Cancel
                    </button>

                    <button
                        onClick={() => formik.handleSubmit()}
                        className="btn btn-primary"
                        type="button"
                        disabled={updating}
                    >
                        {updating ? "Processing..." : scheduleNext ? "Complete & Schedule Next" : "Mark As Completed"}
                    </button>
                </>
            }
        >
            <div className="grid grid-cols-12 gap-4">
                {/* Lead Information */}
                <div className="col-span-12 flex justify-between items-center p-3 bg-gray-50 rounded-lg">
                    <label className="text-gray-500 font-medium">Lead</label>
                    <label className="text-black font-semibold">
                        {data.lead?.lead_name || 'N/A'}
                        {/* <span className="text-sm text-gray-500 ml-2">({data.lead?.lead_mobile})</span> */}
                    </label>
                </div>



                {/* Follow-up Summary */}
                <div className="col-span-12">
                    <div className="border rounded bg-blue-50 p-4">
                        <label className="font-semibold text-blue-800 mb-1 block">Follow-Up Summary</label>
                        <label className="text-sm text-blue-700">
                            Document what happened during this follow-up and plan your next action
                        </label>
                    </div>
                </div>

                <div className="col-span-12">
                    <form className="grid grid-cols-12 gap-4">
                        {/* Outcomes */}
                        <div className="col-span-12">
                            <label className="block mb-1 font-medium">
                                Outcome <span className="text-red-500">*</span>
                            </label>
                            <Select
                                options={outcomesOptions}
                                value={outcomesOptions.find(o => o.value === formik.values.outcomes)}
                                onChange={(val: any) => {
                                    formik.setFieldValue("outcomes", val?.value || "");
                                    formik.setFieldTouched("outcomes", true);
                                }}
                                placeholder="Select outcome"
                            />
                            {formik.touched.outcomes && formik.errors.outcomes && (
                                <p className="text-red-500 text-sm mt-1">{formik.errors.outcomes as string}</p>
                            )}
                        </div>

                        {/* Comments */}
                        <div className="col-span-12">
                            <label className="block mb-1 font-medium">Comments</label>
                            <textarea
                                name="comments"
                                rows={2}
                                className="form-textarea w-full"
                                value={formik.values.comments}
                                onChange={formik.handleChange}
                                onBlur={formik.handleBlur}
                                placeholder="Add your comments here..."
                            />
                        </div>

                        {/* Schedule Next Follow-up */}
                        <div className="col-span-12">
                            <label className="inline-flex items-center cursor-pointer">
                                <input
                                    type="checkbox"
                                    className="form-checkbox rounded border-gray-300 text-primary focus:ring-primary"
                                    checked={scheduleNext}
                                    onChange={(e) => setScheduleNext(e.target.checked)}
                                />
                                <span className="ml-2 text-gray-700">Schedule Next Follow Up</span>
                            </label>
                        </div>

                        {/* Next Follow-up Fields */}
                        {scheduleNext && (
                            <div className="col-span-12">
                                <div className="border-t pt-4 mt-2">
                                    <label className="font-semibold text-gray-700 mb-3 block">Next Follow-Up Details</label>
                                    <div className="grid grid-cols-12 gap-3">
                                        <div className="col-span-12">
                                            <label className="block mb-1 font-medium">
                                                Title <span className="text-red-500">*</span>
                                            </label>
                                            <input
                                                name="next_title"
                                                className="form-input w-full"
                                                value={formik.values.next_title}
                                                onChange={formik.handleChange}
                                                onBlur={formik.handleBlur}
                                                placeholder="Enter follow-up title"
                                            />
                                            {formik.touched.next_title && formik.errors.next_title && (
                                                <p className="text-red-500 text-sm mt-1">{formik.errors.next_title as string}</p>
                                            )}
                                        </div>

                                        <div className="col-span-6">
                                            <label className="block mb-1 font-medium">
                                                Mode <span className="text-red-500">*</span>
                                            </label>
                                            <Select
                                                options={modeOption}
                                                value={modeOption.find(o => o.value === formik.values.next_mode)}
                                                onChange={(val: any) => {
                                                    formik.setFieldValue("next_mode", val?.value || "");
                                                    formik.setFieldTouched("next_mode", true);
                                                }}
                                                placeholder="Select mode"
                                            />
                                            {formik.touched.next_mode && formik.errors.next_mode && (
                                                <p className="text-red-500 text-sm mt-1">{formik.errors.next_mode as string}</p>
                                            )}
                                        </div>

                                        <div className="col-span-6">
                                            <label className="block mb-1 font-medium">
                                                Priority <span className="text-red-500">*</span>
                                            </label>
                                            <Select
                                                options={priorityOptions}
                                                value={priorityOptions.find(o => o.value === formik.values.next_priority)}
                                                onChange={(val: any) => {
                                                    formik.setFieldValue("next_priority", val?.value || "medium");
                                                    formik.setFieldTouched("next_priority", true);
                                                }}
                                                placeholder="Select priority"
                                            />
                                            {formik.touched.next_priority && formik.errors.next_priority && (
                                                <p className="text-red-500 text-sm mt-1">{formik.errors.next_priority as string}</p>
                                            )}
                                        </div>

                                        <div className="col-span-12">
                                            <label className="block mb-1 font-medium">Description</label>
                                            <textarea
                                                name="next_description"
                                                rows={2}
                                                className="form-textarea w-full"
                                                value={formik.values.next_description}
                                                onChange={formik.handleChange}
                                                onBlur={formik.handleBlur}
                                                placeholder="Enter description (optional)"
                                            />
                                        </div>

                                        <div className="col-span-12">
                                            <label className="block mb-1 font-medium">
                                                Due Date & Time <span className="text-red-500">*</span>
                                            </label>
                                            <DateTimePicker
                                                value={formik.values.next_date_time || undefined}
                                                onChange={(val) => {
                                                    formik.setFieldValue("next_date_time", val);
                                                    formik.setFieldTouched("next_date_time", true);
                                                }}
                                                placeholder="Pick date & time"
                                            />
                                            {formik.touched.next_date_time && formik.errors.next_date_time && (
                                                <p className="text-red-500 text-sm mt-1">{formik.errors.next_date_time as string}</p>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        )}
                    </form>
                </div>
            </div>
        </Modal>
    );
};

export default UpdateStatus;
