import { useFormik } from "formik";
import * as Yup from "yup";
import Modal from "../../components/Modals";
import MonthPicker from "../../components/MonthPicker";
import { useState } from "react";

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (data: any) => void;
    kraData?: any;
}

const EditKRA = ({ open, onClose, onSave, kraData }: Props) => {
    const [loading, setLoading] = useState(false);
    const [selectedMonth, setSelectedMonth] = useState<Date>(
        kraData?.month_year ? new Date(kraData.month_year) : new Date()
    );

    const validationSchema = Yup.object({
        kra_title: Yup.string().required("KRA Title is required"),
        weightage: Yup.number()
            .required("Weightage is required")
            .min(0, "Weightage must be at least 0")
            .max(100, "Weightage cannot exceed 100"),
        description: Yup.string().nullable(),
        month_year: Yup.string().required("Month/Year is required"),
    });

    const getInitialValues = () => {
        if (kraData) {
            return {
                kra_title: kraData.kra_title || "",
                weightage: kraData.weightage || 0,
                description: kraData.description || "",
                month_year: kraData.month_year || "",
            };
        }
        return {
            kra_title: "",
            weightage: 0,
            description: "",
            month_year: "",
        };
    };

    const formik = useFormik({
        enableReinitialize: true,
        initialValues: getInitialValues(),
        validationSchema,
        onSubmit: async (values) => {
            setLoading(true);
            await onSave(values);
            setLoading(false);
            onClose();
        },
    });

    const handleMonthChange = (date: Date | null) => {
        if (date) {
            setSelectedMonth(date);
            const formattedDate = date.toISOString().split('T')[0];
            formik.setFieldValue('month_year', formattedDate);
            formik.setFieldTouched('month_year', true);
        }
    };

    if (!open) return null;

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Edit KRA"
            maxWidth="max-w-md"
            footer={
                <>
                    <button
                        onClick={onClose}
                        className="btn btn-outline-danger"
                        type="button"
                        disabled={loading}
                    >
                        Cancel
                    </button>
                    <button
                        onClick={() => formik.handleSubmit()}
                        className="btn btn-primary"
                        type="button"
                        disabled={loading}
                    >
                        {loading ? "Updating..." : "Update KRA"}
                    </button>
                </>
            }
        >
            <form className="space-y-4">
                {/* Month/Year Selection */}
                <div>
                    <label className="block text-sm font-medium mb-1">
                        Month/Year <span className="text-danger">*</span>
                    </label>
                    <MonthPicker
                        value={selectedMonth}
                        onChange={handleMonthChange}
                    />
                    {formik.touched.month_year && formik.errors.month_year && (
                        <p className="text-red-500 text-sm mt-1">
                            {formik.errors.month_year as string}
                        </p>
                    )}
                </div>

                <div>
                    <label className="block text-sm font-medium mb-1">
                        KRA Title <span className="text-danger">*</span>
                    </label>
                    <input
                        name="kra_title"
                        className="form-input w-full"
                        value={formik.values.kra_title}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        disabled={loading}
                        placeholder="Enter KRA title"
                    />
                    {formik.touched.kra_title && formik.errors.kra_title && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.kra_title as string}</p>
                    )}
                </div>

                <div>
                    <label className="block text-sm font-medium mb-1">
                        Weightage (%) <span className="text-danger">*</span>
                    </label>
                    <input
                        name="weightage"
                        type="number"
                        className="form-input w-full"
                        value={formik.values.weightage}
                        onChange={formik.handleChange}
                        onBlur={formik.handleBlur}
                        disabled={loading}
                        placeholder="Enter weightage (0-100)"
                        min="0"
                        max="100"
                    />
                    {formik.touched.weightage && formik.errors.weightage && (
                        <p className="text-red-500 text-sm mt-1">{formik.errors.weightage as string}</p>
                    )}
                </div>

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

export default EditKRA;
