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

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (data: any) => Promise<boolean>;
}
type OptionType = {
  value: string;
  label: string;
};
const AddReminder = ({ open, onClose, onSave }: Props) => {
    const [leads, setLeads] = useState<OptionType[]>([]);
    const [loadingLeads, setLoadingLeads] = useState(false);

    // Fetch leads for dropdown
    useEffect(() => {
        const fetchLeads = async () => {
            setLoadingLeads(true);
            try {
                const response = await api.get('/lead/list', { params: { per_page: 100 } });
                if (response.data.status === true) {
                    const leadOptions = response.data.data.data.map((lead: any) => ({
                        value: lead.id,
                        label: `${lead.lead_name} (${lead.lead_mobile})`
                    }));
                    setLeads(leadOptions);
                }
            } catch (error) {
                console.error('Error fetching leads:', error);
                toast.error('Failed to load leads');
            } finally {
                setLoadingLeads(false);
            }
        };

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

    // Helper function to format date to YYYY-MM-DD
    const formatDateToLocal = (dateString: string): string => {
        if (!dateString) return '';

        try {
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return dateString;

            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');

            return `${year}-${month}-${day}`;
        } catch (error) {
            return dateString;
        }
    };

    // Helper function to format time to HH:mm:ss
    const formatTimeToLocal = (timeString: string): string => {
        if (!timeString) return '';

        try {
            // If it's already in HH:mm format, just add seconds
            if (/^\d{2}:\d{2}$/.test(timeString)) {
                return `${timeString}:00`;
            }

            // If it's a full datetime string, extract time
            const date = new Date(timeString);
            if (!isNaN(date.getTime())) {
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                return `${hours}:${minutes}:00`;
            }

            return timeString;
        } catch (error) {
            return timeString;
        }
    };

    const validationSchema = Yup.object({
        title: Yup.string().required("Title is required"),
        lead_id: Yup.number().required("Lead is required"),
        priority: Yup.string().required("Priority is required"),
        mode: Yup.string().required("Mode is required"),
        reminder_date: Yup.string().required("Date is required"),
        reminder_time: Yup.string().required("Time is required"),
        description: Yup.string().nullable(),
        assign_to: Yup.number().nullable(),
    });

    const formik = useFormik({
        initialValues: {
            title: "",
            lead_id: "",
            priority: "",
            mode: "",
            reminder_date: "",
            reminder_time: "",
            description: "",
            assign_to: "",
        },
        validationSchema,
        onSubmit: async (values) => {
            // Format dates before sending to API
            const formattedValues = {
                ...values,
                reminder_date: formatDateToLocal(values.reminder_date),
                reminder_time: formatTimeToLocal(values.reminder_time),
            };

            console.log('Original values:', values);
            console.log('Formatted values:', formattedValues);

            const success = await onSave(formattedValues);
            if (success) {
                formik.resetForm();
                onClose();
            }
        },
    });

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

    const modeOption = [
        { value: "Call", label: "Call" },
        { value: "WhatsApp", label: "WhatsApp" },
        { value: "Visit", label: "Visit" },
        { value: "Email", label: "Email" },
    ];

    return (
        <Modal
            open={open}
            onClose={() => {
                formik.resetForm();
                onClose();
            }}
            title="Add Reminder"
            maxWidth="max-w-2xl"
            footer={
                <>
                    <button
                        onClick={() => {
                            formik.resetForm();
                            onClose();
                        }}
                        className="btn btn-outline-danger"
                        type="button"
                    >
                        Cancel
                    </button>
                    <button
                        onClick={() => formik.handleSubmit()}
                        className="btn btn-primary"
                        type="button"
                    >
                        Add Reminder
                    </button>
                </>
            }
        >
            <form className="grid grid-cols-12 gap-4">
                <div className="col-span-6">
                    <label className="block mb-1 font-medium">Title <span className="text-danger">*</span></label>
                    <input
                        name="title"
                        className="form-input w-full"
                        value={formik.values.title}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        placeholder="Enter reminder title"
                    />
                    {formik.touched.title && formik.errors.title && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.title}</p>
                    )}
                </div>

                <div className="col-span-6">
                    <label className="block mb-1 font-medium">Link To Lead <span className="text-danger">*</span></label>
                    <Select
                        options={leads}
                        value={leads.find(o => o.value === formik.values.lead_id)}
                        onChange={(val: any) => {
                            formik.setFieldValue("lead_id", val?.value || "");
                            formik.setFieldTouched("lead_id", true);
                        }}
                        placeholder="Select lead"
                        isLoading={loadingLeads}
                    />
                    {formik.touched.lead_id && formik.errors.lead_id && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.lead_id}</p>
                    )}
                </div>

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

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

                <div className="col-span-6">
                    <label className="block mb-1 font-medium">Date <span className="text-danger">*</span></label>
                    <Datepicker
                        value={formik.values.reminder_date}
                        onChange={(val) => {
                            formik.setFieldValue("reminder_date", val);
                            formik.setFieldTouched("reminder_date", true);
                        }}
                        placeholder="Pick date"
                    />
                    {formik.touched.reminder_date && formik.errors.reminder_date && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.reminder_date}</p>
                    )}
                </div>

                <div className="col-span-6">
                    <label className="block mb-1 font-medium">Time <span className="text-danger">*</span></label>
                    <Timepicker
                        value={formik.values.reminder_time}
                        onChange={(val) => {
                            formik.setFieldValue("reminder_time", val);
                            formik.setFieldTouched("reminder_time", true);
                        }}
                        placeholder="Pick time"
                    />
                    {formik.touched.reminder_time && formik.errors.reminder_time && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.reminder_time}</p>
                    )}
                </div>

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

export default AddReminder;
