/* eslint-disable @typescript-eslint/no-unused-vars */
import {
  Button,
  LoadingOverlay,
  Modal,
  ModalProps,
  NumberInput,
  TextInput,
} from "@mantine/core";
import { useForm, zodResolver } from "@mantine/form";
import _ from "lodash";
import { useEffect, useRef, useState } from "react";
import { z } from "zod";
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"),
  arrival_offset_seconds: z
    .number({ message: "Arrival offset seconds is required" })
    .refine((val) => val >= 60, {
      message: "Arrival offset seconds must be at least 60 seconds (1 minute)",
    }),
    early_tracking_seconds: z
    .number({ message: "Early login seconds is required" })
    .refine((val) => val >= 600, {
      message: "Early login seconds must be at least 600 seconds (10 minute)",
    }),
};

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

  const [loading, setLoading] = useState(false);

  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 () => {
          setLoading(true);
          console.log(
            "%csrc/components/web-bid/web-bid-modal.tsx:54 values",
            "color: #007acc;",
            values
          );
          const result = await updateWebBid(values);
          setLoading(false);

          if (!result) return;

          props.onClose();

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

      setLoading(true);
      const result = await createWebBid({
        url,
        origin_url,
        arrival_offset_seconds,
        early_tracking_seconds
      } as IWebBid);
      setLoading(false);

      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
      className="relative"
      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
          withAsterisk
          className="col-span-2"
          size="sm"
          label="Domain"
          {...form.getInputProps("origin_url")}
        />
        <TextInput
          withAsterisk
          className="col-span-2"
          size="sm"
          label="Tracking url"
          {...form.getInputProps("url")}
        />

        <NumberInput
          description="Note: that only integer minutes are accepted."
          className="col-span-2"
          size="sm"
          label={`Arrival offset seconds (${
            form.getValues()["arrival_offset_seconds"] / 60
          } minutes)`}
          placeholder="msg: 300"
          {...form.getInputProps("arrival_offset_seconds")}
        />
        <NumberInput
          description="Note: that only integer minutes are accepted."
          className="col-span-2"
          size="sm"
          label={`Early tracking seconds (${
            form.getValues()["early_tracking_seconds"] / 60
          } minutes)`}
          placeholder="msg: 600"
          {...form.getInputProps("early_tracking_seconds")}
        />

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

      <LoadingOverlay
        visible={loading}
        zIndex={1000}
        overlayProps={{ blur: 2 }}
      />
    </Modal>
  );
}
