/* eslint-disable @typescript-eslint/no-unused-vars */
import {
  Button,
  LoadingOverlay,
  Modal,
  ModalProps,
  Select,
  Textarea,
  TextInput,
} from "@mantine/core";
import { useForm, zodResolver } from "@mantine/form";
import _ from "lodash";
import { useEffect, useRef, useState } from "react";
import { z } from "zod";
import { createScrapConfig, updateScrapConfig } from "../../apis/scrap";
import { useConfirmStore } from "../../lib/zustand/use-confirm";
import { IScrapConfig, IWebBid } from "../../system/type";
export interface IScrapConfigModelProps extends ModalProps {
  data: IWebBid | null;
  onUpdated?: () => void;
}

const schema = z.object({
  search_url: z
    .string()
    .url({ message: "Url is invalid" })
    .min(1, { message: "Url is required" }),
  keywords: z
    .string({ message: "Keyword is required" })
    .min(1, { message: "Keyword is required" })
    .optional(),
  enable: z.enum(["1", "0"], { required_error: "Enable is required" }),
});

export default function ScrapConfigModal({
  data,
  onUpdated,
  ...props
}: IScrapConfigModelProps) {
  const form = useForm<IScrapConfig>({
    validate: zodResolver(schema),
  });

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

  const prevData = useRef<IScrapConfig | null>(data?.scrap_config);

  const { setConfirm } = useConfirmStore();

  const handleSubmit = async (values: typeof form.values) => {
    if (data?.scrap_config) {
      setConfirm({
        title: "Update ?",
        message: `This config will be update`,
        handleOk: async () => {
          setLoading(true);
          const result = await updateScrapConfig({
            ...values,
            id: data.scrap_config.id,
          });
          setLoading(false);

          if (!result) return;

          props.onClose();

          if (onUpdated) {
            onUpdated();
          }
        },
        okButton: {
          color: "blue",
          value: "Update",
        },
      });
    } else {
      setLoading(true);
      const result = await createScrapConfig({
        ...values,
        web_id: data?.id || 0,
      });
      setLoading(false);

      if (!result) return;

      props.onClose();

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

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

    const values = {
      ...data.scrap_config,
      enable: (data.scrap_config?.enable === undefined
        ? "1"
        : data.scrap_config.enable
        ? "1"
        : "0") as "0" | "1",
    };

    form.setValues(values);

    prevData.current = values;
    // 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]);

  return (
    <Modal
      className="relative"
      classNames={{
        header: "!flex !item-center !justify-center w-full",
      }}
      {...props}
      size={"xl"}
      title={<span className="text-xl font-bold">Scrap config</span>}
      centered
    >
      <form
        onSubmit={form.onSubmit(handleSubmit)}
        className="grid grid-cols-2 gap-2.5"
      >
        <Select
          className="col-span-2"
          label="Enable scrape"
          defaultChecked={true}
          defaultValue={"1"}
          data={[
            {
              label: "Enbale",
              value: "1",
            },
            {
              label: "Disable",
              value: "0",
            },
          ]}
          {...form.getInputProps("enable")}
        />
        <TextInput
          className="col-span-2"
          size="sm"
          label="Search url"
          withAsterisk
          description="Replace query keyword in url with phrase {{keyword}}"
          placeholder="https://www.abc.com/search?q={{keyword}}"
          {...form.getInputProps("search_url")}
        />

        <Textarea
          className="col-span-2"
          size="sm"
          label="Keywords"
          rows={4}
          placeholder="msg: Cisco"
          description={"Different keywords must be separated by commas."}
          {...form.getInputProps("keywords")}
        />

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

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