import { Dialog, Transition } from '@headlessui/react';
import { Fragment, useEffect } from 'react';
import { DialogPanel, TransitionChild } from '@headlessui/react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { UpdateProductFormValues, updateProductSchema } from '../types/form';
import IconX from '../../../components/Icon/IconX';
import { useTranslation } from 'react-i18next';
import Swal from 'sweetalert2';
import { useProductCategories } from '../../productCategories/api/getProductCategories';
import { useProductCollections } from '../../productCollections/api/getProductCollections';
import { useProductColours } from '../../productColours/api/getProductColours';
import { useProductSizes } from '../../productSizes/api/getProductSizes';
import IconLoader from '../../../components/Icon/IconLoader';
import { Product } from '../types/api';
import { useUpdateProduct } from '../api/updateProduct';

interface Props {
    isOpen: boolean;
    onClose: () => void;
    product: Product | null;
}

export const EditProductModal = ({ isOpen, onClose, product }: Props) => {
    const { t } = useTranslation();

    const categoriesQuery = useProductCategories();
    const categoryOptions =
        categoriesQuery.data?.map((category) => ({
            value: category.id,
            label: category.name,
        })) || [];

    const collectionsQuery = useProductCollections();
    const collectionOptions =
        collectionsQuery.data?.map((collection) => ({
            value: collection.id,
            label: collection.name,
        })) || [];

    const coloursQuery = useProductColours();
    const colourOptions =
        coloursQuery.data?.map((colour) => ({
            value: colour.id,
            label: colour.name,
        })) || [];

    const sizesQuery = useProductSizes();
    const sizeOptions =
        sizesQuery.data?.map((size) => ({
            value: size.id,
            label: size.name,
        })) || [];

    const updateProduct = useUpdateProduct({
        mutationConfig: {
            onSuccess: () => {
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: 'Product updated successfully',
                });
                onClose();
            },
        },
    });

    const {
        register,
        handleSubmit,
        formState: { errors },
        reset,
    } = useForm<UpdateProductFormValues>({
        resolver: zodResolver(updateProductSchema),
    });

    useEffect(() => {
        if (product) {
            reset({
                ...product,
                category_id: product.category.id,
                collection_id: product.collection.id,
                colour_id: product.colour.id,
                size_id: product.size.id,
            });
        }
    }, [product, reset]);

    const submit = async (data: UpdateProductFormValues) => {
        if (product) {
            await updateProduct.mutateAsync({ productId: product.id, data });
        }
    };

    return (
        <Transition appear show={isOpen} as={Fragment}>
            <Dialog as="div" open={isOpen} onClose={onClose} className="relative z-[51]">
                <TransitionChild as={Fragment} enter="ease-out duration-300" enterFrom="opacity-0" enterTo="opacity-100" leave="ease-in duration-200" leaveFrom="opacity-100" leaveTo="opacity-0">
                    <div className="fixed inset-0 bg-[black]/60" />
                </TransitionChild>

                <div className="fixed inset-0 overflow-y-auto">
                    <div className="flex min-h-full items-center justify-center px-4 py-8">
                        <TransitionChild
                            as={Fragment}
                            enter="ease-out duration-300"
                            enterFrom="opacity-0 scale-95"
                            enterTo="opacity-100 scale-100"
                            leave="ease-in duration-200"
                            leaveFrom="opacity-100 scale-100"
                            leaveTo="opacity-0 scale-95"
                        >
                            <DialogPanel className="panel border-0 p-0 rounded-lg overflow-hidden w-full max-w-3xl text-black dark:text-white-dark">
                                <button type="button" onClick={onClose} className="absolute top-4 right-4 text-gray-400 hover:text-gray-800">
                                    <IconX />
                                </button>

                                <div className="text-lg font-medium bg-[#fbfbfb] dark:bg-[#121c2c] px-5 py-3">Edit Product</div>

                                <div className="p-5">
                                    <form onSubmit={handleSubmit(submit)} className="space-y-6">
                                        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                            <div>
                                                <label>
                                                    Name <span className="text-red-500">*</span>
                                                </label>
                                                <input {...register('name')} className="form-input" placeholder="Enter Name" />
                                                {errors.name && <div className="text-red-500 text-sm mt-1">{errors.name.message}</div>}
                                            </div>
                                            <div>
                                                <label>
                                                    Category <span className="text-red-500">*</span>
                                                </label>
                                                <select {...register('category_id')} className="form-select">
                                                    <option value="">Select Category</option>
                                                    {categoryOptions.map((opt) => (
                                                        <option key={opt.value} value={String(opt.value)}>
                                                            {opt.label}
                                                        </option>
                                                    ))}
                                                </select>
                                                {errors.category_id && <div className="text-red-500 text-sm mt-1">{errors.category_id.message}</div>}
                                            </div>
                                            <div>
                                                <label>
                                                    Collection <span className="text-red-500">*</span>
                                                </label>
                                                <select {...register('collection_id')} className="form-select">
                                                    <option value="">Select Collection</option>
                                                    {collectionOptions.map((opt) => (
                                                        <option key={opt.value} value={String(opt.value)}>
                                                            {opt.label}
                                                        </option>
                                                    ))}
                                                </select>
                                                {errors.collection_id && <div className="text-red-500 text-sm mt-1">{errors.collection_id.message}</div>}
                                            </div>
                                            <div>
                                                <label>
                                                    Colour <span className="text-red-500">*</span>
                                                </label>
                                                <select {...register('colour_id')} className="form-select">
                                                    <option value="">Select Colour</option>
                                                    {colourOptions.map((opt) => (
                                                        <option key={opt.value} value={String(opt.value)}>
                                                            {opt.label}
                                                        </option>
                                                    ))}
                                                </select>
                                                {errors.colour_id && <div className="text-red-500 text-sm mt-1">{errors.colour_id.message}</div>}
                                            </div>
                                            <div>
                                                <label>
                                                    Size <span className="text-red-500">*</span>
                                                </label>
                                                <select {...register('size_id')} className="form-select">
                                                    <option value="">Select Size</option>
                                                    {sizeOptions.map((opt) => (
                                                        <option key={opt.value} value={String(opt.value)}>
                                                            {opt.label}
                                                        </option>
                                                    ))}
                                                </select>
                                                {errors.size_id && <div className="text-red-500 text-sm mt-1">{errors.size_id.message}</div>}
                                            </div>
                                            <div>
                                                <label>
                                                    Price <span className="text-red-500">*</span>
                                                </label>
                                                <input type="number" {...register('price')} className="form-input" placeholder="Enter Price" />
                                                {errors.price && <div className="text-red-500 text-sm mt-1">{errors.price.message}</div>}
                                            </div>
                                            <div>
                                                <label>
                                                    HPP <span className="text-red-500">*</span>
                                                </label>
                                                <input type="number" {...register('hpp')} className="form-input" placeholder="Enter HPP" />
                                                {errors.hpp && <div className="text-red-500 text-sm mt-1">{errors.hpp.message}</div>}
                                            </div>
                                            <div>
                                                <label>
                                                    Unit <span className="text-red-500">*</span>
                                                </label>
                                                <input {...register('unit_of_measure')} className="form-input" placeholder="Enter Unit" />
                                                {errors.unit_of_measure && <div className="text-red-500 text-sm mt-1">{errors.unit_of_measure.message}</div>}
                                            </div>
                                        </div>

                                        <div>
                                            <label>Description</label>
                                            <textarea {...register('description')} className="form-textarea w-full" rows={4} placeholder="Enter Description" />
                                            {errors.description && <div className="text-red-500 text-sm mt-1">{errors.description.message}</div>}
                                        </div>

                                        <div className="flex gap-4 items-center">
                                            <label className="flex items-center gap-2">
                                                <input type="checkbox" {...register('is_raw_material')} />
                                                Raw Material
                                            </label>
                                            <label className="flex items-center gap-2">
                                                <input type="checkbox" {...register('is_finished_good')} />
                                                Finished Good
                                            </label>
                                        </div>

                                        <div className="flex justify-end gap-3 mt-6">
                                            <button type="button" onClick={onClose} className="btn btn-outline-danger disabled:opacity-50" disabled={updateProduct.isPending}>
                                                {t('cancel')}
                                            </button>
                                            <button type="submit" className="btn btn-primary disabled:opacity-50" disabled={updateProduct.isPending}>
                                                {updateProduct.isPending ? <IconLoader className="animate-spin" /> : null}
                                                {t('save')}
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </DialogPanel>
                        </TransitionChild>
                    </div>
                </div>
            </Dialog>
        </Transition>
    );
};
