import { Dialog, Transition } from '@headlessui/react';
import { Fragment, useEffect, useRef } from 'react';
import { DialogPanel, TransitionChild } from '@headlessui/react';
import { Controller, useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { useUpdateProductColour } from '../api/updateProductColour';
import { UpdateProductColourFormValues, updateProductColourSchema } from '../types/form';
import { ProductColour } from '../types/api';
import IconX from '../../../components/Icon/IconX';
import Swal from 'sweetalert2';
import { useTranslation } from 'react-i18next';
import IconLoader from '../../../components/Icon/IconLoader';

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

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

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

    const {
        register,
        handleSubmit,
        control,
        formState: { errors },
        reset,
    } = useForm<UpdateProductColourFormValues>({
        resolver: zodResolver(updateProductColourSchema),
    });

    useEffect(() => {
        if (colour) {
            reset({
                name: colour.name,
                code: colour.code,
                hex: colour.hex,
            });
        }
    }, [colour, reset]);

    const onSubmit = async (data: UpdateProductColourFormValues) => {
        if (colour) {
            await updateColour.mutateAsync({ colourId: colour.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-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">Edit Product Collection</div>

                                <div className="p-5">
                                    <form onSubmit={handleSubmit(onSubmit)} 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>
                                        <Controller
                                            name="hex"
                                            control={control}
                                            render={({ field }) => {
                                                const colorRef = useRef<HTMLInputElement>(null);

                                                return (
                                                    <div>
                                                        <label className="block mb-1 font-medium text-gray-700 dark:text-white">
                                                            Hex <span className="text-red-500">*</span>
                                                        </label>
                                                        <div className="flex items-center gap-3">
                                                            {/* Custom Color Picker Circle */}
                                                            <button
                                                                type="button"
                                                                className="w-10 h-10 rounded-full border border-gray-300 shadow"
                                                                style={{ backgroundColor: field.value }}
                                                                onClick={() => colorRef.current?.click()}
                                                            />

                                                            {/* Hidden input[type=color] */}
                                                            <input type="color" ref={colorRef} value={field.value} onChange={(e) => field.onChange(e.target.value)} className="sr-only" />

                                                            {/* Input Text */}
                                                            <input
                                                                type="text"
                                                                value={field.value}
                                                                onChange={(e) => field.onChange(e.target.value)}
                                                                className="form-input flex-1"
                                                                placeholder="#FFFFFF"
                                                            />
                                                        </div>

                                                        {errors.hex && <p className="text-red-500 text-sm mt-1">{errors.hex.message}</p>}
                                                    </div>
                                                );
                                            }}
                                        />

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