/* eslint-disable @typescript-eslint/no-unused-vars */
import { Button, Modal, ModalProps, TextInput } from '@mantine/core';
import { useForm, zodResolver } from '@mantine/form';
import _ from 'lodash';
import { useEffect, useRef } from 'react';
import { z } from 'zod';
import { updateBid } from '../../apis/bid';
import { createWebBid, updateWebBid } from '../../apis/web-bid';
import { useConfirmStore } from '../../lib/zustand/use-confirm';
import { IWebBid } from '../../system/type';
import { extractDomain } from '../../utils';
export interface IWebBidModelProps extends ModalProps {
    data: IWebBid | null;
    onUpdated?: () => void;
}

const schema = {
    url: z.string({ message: 'Url is required' }).url('Invalid url format'),
};

export default function WebBidModal({ data, onUpdated, ...props }: IWebBidModelProps) {
    const form = useForm({
        validate: zodResolver(z.object(schema)),
    });

    const prevData = useRef<IWebBid | null>(data);

    const { setConfirm } = useConfirmStore();

    const handleSubmit = async (values: typeof form.values) => {
        if (data) {
            setConfirm({
                title: 'Update ?',
                message: `This web will be update`,
                handleOk: async () => {
                    const result = await updateWebBid(values);

                    if (!result) return;

                    props.onClose();

                    if (onUpdated) {
                        onUpdated();
                    }
                },
                okButton: {
                    color: 'blue',
                    value: 'Update',
                },
            });
        } else {
            const { url, origin_url } = values;

            const result = await createWebBid({ url, origin_url } as IWebBid);

            if (!result) return;

            props.onClose();

            if (onUpdated) {
                onUpdated();
            }
        }
    };

    useEffect(() => {
        form.reset();
        if (!data) return;

        form.setValues(data);

        prevData.current = data;
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data]);

    useEffect(() => {
        if (!props.opened) {
            form.reset();
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [props.opened]);

    useEffect(() => {
        if (form.values?.url) {
            form.setFieldValue('origin_url', extractDomain(form.values.url));
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [form.values]);

    return (
        <Modal
            classNames={{
                header: '!flex !item-center !justify-center w-full',
            }}
            {...props}
            size={'xl'}
            title={<span className="text-xl font-bold">Web</span>}
            centered
        >
            <form onSubmit={form.onSubmit(handleSubmit)} className="grid grid-cols-2 gap-2.5">
                <TextInput className="col-span-2" size="sm" label="Domain" {...form.getInputProps('origin_url')} />
                <TextInput className="col-span-2" size="sm" label="Tracking url" {...form.getInputProps('url')} />

                <Button disabled={_.isEqual(form.getValues(), prevData.current)} className="col-span-2" type="submit" fullWidth size="sm" mt="md">
                    {data ? 'Update' : 'Create'}
                </Button>
            </form>
        </Modal>
    );
}
