import { Dialog, Transition } from '@headlessui/react';
import { Fragment } from 'react';
import { DialogPanel, TransitionChild } from '@headlessui/react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import IconX from '../../../components/Icon/IconX';
import IconLoader from '../../../components/Icon/IconLoader';
import { useTranslation } from 'react-i18next';
import Swal from 'sweetalert2';
import { useCreateProductSize } from '../api/createProductSize';
import { createProductSizeSchema, CreateProductSizeFormValues } from '../types/form';

interface Props {
    isOpen: boolean;
    onClose: () => void;
}

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

    const createSize = useCreateProductSize({
        mutationConfig: {
            onSuccess: () => {
                Swal.fire({
                    icon: 'success',
                    title: 'Success',
                    text: 'Product size created successfully',
                });
                onClose();
            },
        },
    });

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

    const submit = async (data: CreateProductSizeFormValues) => {
        await createSize.mutateAsync({ data });
        reset();
    };

    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-lg 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">Create Product Size</div>

                                <div className="p-5">
                                    <form onSubmit={handleSubmit(submit)} className="space-y-6">
                                        <div>
                                            <label>
                                                Code <span className="text-red-500">*</span>
                                            </label>
                                            <input
                                                {...register('code')}
                                                className="form-input"
                                                placeholder="Enter Code"
                                                onChange={(e) => {
                                                    const upper = e.target.value.toUpperCase();
                                                    e.target.value = upper;
                                                    // Trigger update ke form
                                                    return register('code').onChange(e);
                                                }}
                                            />
                                            {errors.code && <div className="text-red-500 text-sm mt-1">{errors.code.message}</div>}
                                        </div>

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