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

type Item = {
    name: string;
    qty: number;
};

type FormValues = {
    name: string; // Changed from kitName to name
    description: string;
    items: Item[];
};

const EditMaterials = ({ open, onClose, onSave, data }: any) => {
    const validationSchema = Yup.object({
        name: Yup.string()
            .required("Kit name is required")
            .min(3, "Kit name must be at least 3 characters")
            .max(255, "Kit name is too long"),
        description: Yup.string(),
        items: Yup.array().of(
            Yup.object({
                name: Yup.string().required("Item name required"),
                qty: Yup.number()
                    .min(1, "Quantity must be at least 1")
                    .required("Qty required")
                    .typeError("Quantity must be a number")
            })
        ).min(1, "At least one item is required")
    });

    const handleSubmit = async (values: FormValues, { resetForm, setSubmitting, setErrors }: any) => {
        try {
            // Prepare payload for API
            const payload = {
                id: data?.id,
                name: values.name,
                description: values.description,
                items: values.items.filter((item: Item) => item.name && item.qty > 0)
            };

            // Call API
            const response = await api.put('/material-kit/update', payload);

            if (response.data.status === 200) {
                toast.success('Material kit updated successfully');
                resetForm();
                onClose();
                if (onSave) {
                    onSave(response.data.data, true);
                }
            } else {
                toast.error(response.data.message || 'Failed to update material kit');
            }
        } catch (error: any) {
            console.error('Error updating material kit:', error);

            if (error.response?.status === 409) {
                toast.error('A material kit with this name already exists');
                setErrors({ name: 'This kit name already exists' });
            } else if (error.response?.status === 422) {
                const errors = error.response.data.errors;
                Object.keys(errors).forEach(key => {
                    toast.error(errors[key][0]);
                });
                setErrors(errors);
            } else {
                toast.error(error.response?.data?.message || 'Failed to update material kit');
            }
        } finally {
            setSubmitting(false);
        }
    };

    return (
        <Formik<FormValues>
            enableReinitialize
            initialValues={{
                name: data?.name || "",
                description: data?.description || "",
                items: data?.items?.length
                    ? data.items
                    : [{ name: "", qty: 1 }]
            }}
            validationSchema={validationSchema}
            onSubmit={handleSubmit}
        >
            {(formik) => {
                const totalQty = formik.values.items.reduce(
                    (sum, item) => sum + (Number(item.qty) || 0),
                    0
                );

                const itemTypes = formik.values.items.filter(item => item.name).length;

                return (
                    <Modal
                        open={open}
                        onClose={() => {
                            formik.resetForm();
                            onClose();
                        }}
                        title="Edit Material Kit"
                        maxWidth="max-w-2xl"
                        footer={
                            <>
                                <button
                                    onClick={() => {
                                        formik.resetForm();
                                        onClose();
                                    }}
                                    className="btn btn-outline-danger"
                                    type="button"
                                    disabled={formik.isSubmitting}
                                >
                                    Cancel
                                </button>

                                <button
                                    onClick={formik.submitForm}
                                    className="btn btn-primary"
                                    type="button"
                                    disabled={formik.isSubmitting}
                                >
                                    {formik.isSubmitting ? 'Updating...' : 'Update Kit'}
                                </button>
                            </>
                        }
                    >
                        <Form className="grid grid-cols-12 gap-4">
                            {/* Kit Name */}
                            <div className="col-span-12">
                                <label className="block text-sm font-medium mb-1">
                                    Kit Name <span className="text-red-500">*</span>
                                </label>
                                <input
                                    name="name"
                                    className={`form-input w-full ${formik.errors.name && formik.touched.name ? 'border-red-500' : ''}`}
                                    value={formik.values.name}
                                    onChange={formik.handleChange}
                                    onBlur={formik.handleBlur}
                                    disabled={formik.isSubmitting}
                                />
                                <ErrorMessage name="name" component="div" className="text-red-500 text-xs mt-1" />
                            </div>

                            {/* Description */}
                            <div className="col-span-12">
                                <label className="block text-sm font-medium mb-1">Description</label>
                                <textarea
                                    name="description"
                                    className="form-textarea w-full"
                                    value={formik.values.description}
                                    onChange={formik.handleChange}
                                    onBlur={formik.handleBlur}
                                    rows={3}
                                    disabled={formik.isSubmitting}
                                />
                                <ErrorMessage name="description" component="div" className="text-red-500 text-xs mt-1" />
                            </div>

                            {/* Items */}
                            <div className="col-span-12">
                                <label className="block text-sm font-medium mb-2">
                                    Items <span className="text-red-500">*</span>
                                </label>

                                <FieldArray name="items">
                                    {(arrayHelpers) => (
                                        <div className="space-y-3">
                                            {formik.values.items.map((item, index) => (
                                                <div key={index} className="flex gap-2 items-start">
                                                    <div className="flex-1">
                                                        <input
                                                            name={`items.${index}.name`}
                                                            placeholder="Item Name"
                                                            className={`form-input w-full ${ typeof formik.errors.items?.[index] !== "string" && formik.errors.items?.[index]?.name && formik.touched.items?.[index]?.name ? "border-red-500" : "" }`}
                                                            value={item.name}
                                                            onChange={formik.handleChange}
                                                            onBlur={formik.handleBlur}
                                                            disabled={formik.isSubmitting}
                                                        />
                                                        <ErrorMessage name={`items.${index}.name`} component="div" className="text-red-500 text-xs mt-1" />
                                                    </div>

                                                    <div className="w-24">
                                                        <input
                                                            type="number"
                                                            name={`items.${index}.qty`}
                                                            placeholder="Qty"
                                                            className={`form-input w-full ${ typeof formik.errors.items?.[index] !== "string" && formik.errors.items?.[index]?.qty && formik.touched.items?.[index]?.qty ? "border-red-500" : "" }`}
                                                            value={item.qty}
                                                            onChange={formik.handleChange}
                                                            onBlur={formik.handleBlur}
                                                            min="1"
                                                            disabled={formik.isSubmitting}
                                                        />
                                                        <ErrorMessage name={`items.${index}.qty`} component="div" className="text-red-500 text-xs mt-1" />
                                                    </div>

                                                    {formik.values.items.length > 1 && (
                                                        <button
                                                            type="button"
                                                            onClick={() => arrayHelpers.remove(index)}
                                                            className="mt-1 text-red-500 hover:text-red-700"
                                                            disabled={formik.isSubmitting}
                                                        >
                                                            <IconX />
                                                        </button>
                                                    )}
                                                </div>
                                            ))}

                                            <button
                                                type="button"
                                                onClick={() => arrayHelpers.push({ name: "", qty: 1 })}
                                                className="btn btn-outline-primary flex gap-2"
                                                disabled={formik.isSubmitting}
                                            >
                                                <IconPlus />
                                                Add Item
                                            </button>

                                            {typeof formik.errors.items === 'string' && (
                                                <div className="text-red-500 text-xs mt-1">{formik.errors.items}</div>
                                            )}
                                        </div>
                                    )}
                                </FieldArray>
                            </div>

                            {/* Auto calculation */}
                            <div className="col-span-12 grid grid-cols-2 gap-4 mt-4">
                                <div className="bg-blue-50 p-3 rounded">
                                    <div className="text-sm text-gray-600">Item Types</div>
                                    <div className="text-lg font-semibold text-blue-700">{itemTypes}</div>
                                </div>

                                <div className="bg-green-50 p-3 rounded">
                                    <div className="text-sm text-gray-600">Total Quantity</div>
                                    <div className="text-lg font-semibold text-green-700">{totalQty}</div>
                                </div>
                            </div>

                            {/* Form validation summary */}
                            {formik.isSubmitting && Object.keys(formik.errors).length > 0 && (
                                <div className="col-span-12 bg-red-50 border border-red-200 rounded p-3">
                                    <p className="text-red-600 text-sm">Please fix the following errors:</p>
                                    <ul className="list-disc list-inside text-red-500 text-xs mt-1">
                                        {Object.values(formik.errors).map((error: any, index) => (
                                            <li key={index}>{typeof error === 'string' ? error : 'Please check all fields'}</li>
                                        ))}
                                    </ul>
                                </div>
                            )}
                        </Form>
                    </Modal>
                );
            }}
        </Formik>
    );
};

export default EditMaterials;
