import { useRef, useState } from 'react';
import { Formik, FieldArray, Form } from 'formik';
import * as Yup from 'yup';
import Modal from '../../components/Modals';
import IconX from '../../components/Icon/IconX';
import Button from '../../components/Buttons';
import IconPlus from '../../components/Icon/IconPlus';
import MonthPicker from '../../components/MonthPicker';
import api from '../../api/axios';
import { toast } from 'react-toastify';

interface Props {
    open: boolean;
    onClose: () => void;
    onSave: (data: any) => void;
    staffId?: number;
    kraList?: any[];
}

const AddKPI = ({ open, onClose, onSave, staffId, kraList }: Props) => {
    const formikRef = useRef<any>(null);
    const [loading, setLoading] = useState(false);
    const [selectedMonth, setSelectedMonth] = useState<Date>(new Date());

    const validationSchema = Yup.object({
        month_year: Yup.string().required('Month/Year is required'),
        kras: Yup.array().of(
            Yup.object({
                kra_title: Yup.string().required('KRA Title is required'),
                description: Yup.string().required('Description is required'),
                weightage: Yup.number()
                    .typeError('Must be a number')
                    .required('Weightage required')
                    .min(1, 'Minimum 1%')
                    .max(100, 'Maximum 100%'),
                kpis: Yup.array().of(
                    Yup.object({
                        metric_name: Yup.string().required('Metric name required'),
                        target: Yup.string().required('Target required'),
                        weightage: Yup.number()
                            .typeError('Must be a number')
                            .required('Weightage required')
                            .min(1, 'Minimum 1%')
                            .max(100, 'Maximum 100%'),
                        score: Yup.number()
                            .typeError('Must be a number')
                            .min(0, 'Minimum 0')
                            .max(100, 'Maximum 100'),
                    })
                )
            })
        )
    });

    const handleSubmit = async (values: any) => {
        if (!staffId) {
            toast.error('Staff ID is missing');
            return;
        }

        if (!values.month_year) {
            toast.error('Please select month and year');
            return;
        }

        setLoading(true);
        try {
            // Process each KRA and its KPIs with month/year
            const results = [];

            for (const kra of values.kras) {
                // First create the KRA
                const kraResponse = await api.post(`/staff/kra/${staffId}`, {
                    kra_title: kra.kra_title,
                    weightage: Number(kra.weightage),
                    description: kra.description,
                    month_year: values.month_year, // Add month/year
                });

                if (kraResponse.data.status) {
                    const kraId = kraResponse.data.data.id;

                    // Then create all KPIs for this KRA
                    for (const kpi of kra.kpis) {
                        await api.post(`/staff/kpi/${staffId}`, {
                            kra_id: kraId,
                            metric_name: kpi.metric_name,
                            target: kpi.target,
                            current: '0',
                            score: kpi.score ? Number(kpi.score) : null,
                            weightage: Number(kpi.weightage),
                            month_year: values.month_year, // Add month/year
                        });
                    }
                    results.push(kraResponse.data.data);
                }
            }

            toast.success(`${results.length} KRA(s) with KPIs created successfully for ${formatMonthYear(values.month_year)}`);
            onSave(results);
            onClose();
        } catch (error: any) {
            console.error('Failed to create bulk metrics:', error);
            toast.error(error.response?.data?.message || 'Failed to create bulk metrics');
        } finally {
            setLoading(false);
        }
    };

    const formatMonthYear = (date: string) => {
        const d = new Date(date);
        return d.toLocaleString('default', { month: 'long', year: 'numeric' });
    };

    const handleClose = () => {
        formikRef.current?.resetForm();
        setSelectedMonth(new Date());
        onClose();
    };

    return (
        <Modal
            open={open}
            onClose={handleClose}
            title="Create KRA & KPI Metrics (Bulk)"
            maxWidth="max-w-4xl"
            footer={
                <>
                    <button
                        onClick={handleClose}
                        className="btn btn-outline-danger"
                        type="button"
                        disabled={loading}
                    >
                        Cancel
                    </button>
                    <button
                        onClick={() => formikRef.current?.submitForm()}
                        className="btn btn-primary"
                        type="button"
                        disabled={loading}
                    >
                        {loading ? 'Creating...' : 'Create Metrics'}
                    </button>
                </>
            }
        >
            <Formik
                innerRef={formikRef}
                initialValues={{
                    month_year: '',
                    kras: [
                        {
                            kra_title: '',
                            description: '',
                            weightage: '',
                            kpis: [
                                {
                                    metric_name: '',
                                    target: '',
                                    weightage: '',
                                    score: ''
                                }
                            ]
                        }
                    ]
                }}
                validationSchema={validationSchema}
                onSubmit={handleSubmit}
            >
                {(formik) => (
                    <Form className="space-y-6 overflow-y-auto max-h-[550px] scrollbar-thin scrollbar-thumb-gray-400">
                        {/* Month/Year Selection */}
                        <div className="bg-blue-50 p-4 rounded-lg border border-blue-200">
                            <label className="block text-sm font-medium mb-2 text-blue-700">
                                Select Month/Year <span className="text-red-500">*</span>
                            </label>
                            <MonthPicker
                                value={selectedMonth}
                                onChange={(date) => {
                                    if (date) {
                                        setSelectedMonth(date);
                                        const formattedDate = date.toISOString().split('T')[0];
                                        formik.setFieldValue('month_year', formattedDate);
                                        formik.setFieldTouched('month_year', true);
                                    }
                                }}
                            />
                            {formik.touched.month_year && formik.errors.month_year && (
                                <p className="text-red-500 text-sm mt-1">
                                    {formik.errors.month_year as string}
                                </p>
                            )}
                            <p className="text-xs text-gray-500 mt-2">
                                Selected: {selectedMonth.toLocaleString('default', { month: 'long', year: 'numeric' })}
                            </p>
                        </div>

                        <FieldArray name="kras">
                            {(kraHelpers) => (
                                <>
                                    {formik.values.kras.map((kra, i) => (
                                        <div key={i} className="border p-5 rounded-xl space-y-4 bg-white">
                                            <div className="flex justify-between items-center">
                                                <h3 className="font-semibold text-lg">KRA {i + 1}</h3>
                                                {formik.values.kras.length > 1 && (
                                                    <button
                                                        type="button"
                                                        onClick={() => kraHelpers.remove(i)}
                                                        className="text-red-500 hover:text-red-700"
                                                        disabled={loading}
                                                    >
                                                        <IconX />
                                                    </button>
                                                )}
                                            </div>

                                            <div className="grid grid-cols-3 gap-3">
                                                <div>
                                                    <label className="block text-sm font-medium mb-1">KRA Title *</label>
                                                    <input
                                                        placeholder="e.g., Branch Profitability"
                                                        className="form-input w-full"
                                                        {...formik.getFieldProps(`kras.${i}.kra_title`)}
                                                        disabled={loading}
                                                    />
                                                    {formik.touched?.kras?.[i]?.kra_title &&
                                                        typeof formik.errors?.kras?.[i] !== 'string' &&
                                                        formik.errors?.kras?.[i]?.kra_title && (
                                                            <p className="text-red-500 text-sm mt-1">
                                                                {(formik.errors.kras[i] as any).kra_title}
                                                            </p>
                                                        )}
                                                </div>

                                                <div>
                                                    <label className="block text-sm font-medium mb-1">Weightage (%) *</label>
                                                    <input
                                                        type="number"
                                                        placeholder="Weightage %"
                                                        className="form-input w-full"
                                                        {...formik.getFieldProps(`kras.${i}.weightage`)}
                                                        disabled={loading}
                                                        min="1"
                                                        max="100"
                                                    />
                                                    {formik.touched?.kras?.[i]?.weightage &&
                                                        typeof formik.errors?.kras?.[i] !== 'string' &&
                                                        formik.errors?.kras?.[i]?.weightage && (
                                                            <p className="text-red-500 text-sm mt-1">
                                                                {(formik.errors.kras[i] as any).weightage}
                                                            </p>
                                                        )}
                                                </div>

                                                <div>
                                                    <label className="block text-sm font-medium mb-1">Description *</label>
                                                    <input
                                                        placeholder="Description"
                                                        className="form-input w-full"
                                                        {...formik.getFieldProps(`kras.${i}.description`)}
                                                        disabled={loading}
                                                    />
                                                    {formik.touched?.kras?.[i]?.description &&
                                                        typeof formik.errors?.kras?.[i] !== 'string' &&
                                                        formik.errors?.kras?.[i]?.description && (
                                                            <p className="text-red-500 text-sm mt-1">
                                                                {(formik.errors.kras[i] as any).description}
                                                            </p>
                                                        )}
                                                </div>
                                            </div>

                                            <FieldArray name={`kras.${i}.kpis`}>
                                                {(kpiHelpers) => (
                                                    <div className="bg-gray-50 p-4 rounded space-y-3">
                                                        <label className="font-medium">KPIs for this KRA</label>

                                                        {kra.kpis.map((kpi, j) => (
                                                            <div key={j} className="grid grid-cols-5 gap-2 items-start">
                                                                <div className="col-span-2">
                                                                    <input
                                                                        placeholder="Metric Name *"
                                                                        className="form-input w-full"
                                                                        {...formik.getFieldProps(`kras.${i}.kpis.${j}.metric_name`)}
                                                                        disabled={loading}
                                                                    />
                                                                </div>

                                                                <div>
                                                                    <input
                                                                        placeholder="Target *"
                                                                        className="form-input w-full"
                                                                        {...formik.getFieldProps(`kras.${i}.kpis.${j}.target`)}
                                                                        disabled={loading}
                                                                    />
                                                                </div>

                                                                <div>
                                                                    <input
                                                                        type="number"
                                                                        placeholder="Weight % *"
                                                                        className="form-input w-full"
                                                                        {...formik.getFieldProps(`kras.${i}.kpis.${j}.weightage`)}
                                                                        disabled={loading}
                                                                        min="1"
                                                                        max="100"
                                                                    />
                                                                </div>

                                                                <div className="flex gap-2">
                                                                    <div className="flex-1">
                                                                        <input
                                                                            type="number"
                                                                            placeholder="Score"
                                                                            className="form-input w-full"
                                                                            {...formik.getFieldProps(`kras.${i}.kpis.${j}.score`)}
                                                                            disabled={loading}
                                                                            min="0"
                                                                            max="100"
                                                                        />
                                                                    </div>
                                                                    {kra.kpis.length > 1 && (
                                                                        <button
                                                                            type="button"
                                                                            onClick={() => kpiHelpers.remove(j)}
                                                                            className="text-red-500 hover:text-red-700 mt-1"
                                                                            disabled={loading}
                                                                        >
                                                                            <IconX />
                                                                        </button>
                                                                    )}
                                                                </div>
                                                            </div>
                                                        ))}

                                                        <Button
                                                            variant='secondary'
                                                            type="button"
                                                            onClick={() =>
                                                                kpiHelpers.push({
                                                                    metric_name: '',
                                                                    target: '',
                                                                    weightage: '',
                                                                    score: ''
                                                                })
                                                            }
                                                            disabled={loading}
                                                        >
                                                            <IconPlus />
                                                            Add KPI
                                                        </Button>
                                                    </div>
                                                )}
                                            </FieldArray>
                                        </div>
                                    ))}

                                    <Button
                                        variant='primary'
                                        type="button"
                                        onClick={() =>
                                            kraHelpers.push({
                                                kra_title: '',
                                                description: '',
                                                weightage: '',
                                                kpis: [
                                                    {
                                                        metric_name: '',
                                                        target: '',
                                                        weightage: '',
                                                        score: ''
                                                    }
                                                ]
                                            })
                                        }
                                        disabled={loading}
                                    >
                                        <IconPlus />
                                        Add Another KRA
                                    </Button>
                                </>
                            )}
                        </FieldArray>
                    </Form>
                )}
            </Formik>
        </Modal>
    );
};

export default AddKPI;
