import { ActionIcon, Badge, Box, Menu, Text } from "@mantine/core";
import {
  IconAd,
  IconAdOff,
  IconEdit,
  IconMenu,
  IconSettingsCode,
  IconTrash,
  IconUserEdit,
} from "@tabler/icons-react";
import { useMemo, useRef, useState } from "react";
import {
  deletesWebBid,
  deleteWebBid,
  getWebBids,
  updateWebBid,
} from "../apis/web-bid";
import Table from "../lib/table/table";
import { IColumn, TRefTableFn } from "../lib/table/type";
import { useConfirmStore } from "../lib/zustand/use-confirm";
import { IWebBid } from "../system/type";
import { formatTime } from "../utils";
import { WebAccountModal, WebBidModal } from "../components/web-bid";
import { useDisclosure } from "@mantine/hooks";
import ScrapConfigModal from "../components/web-bid/scrap-config.modal";

export default function WebBids() {
  const refTableFn: TRefTableFn<IWebBid> = useRef({});

  const [clickData, setClickData] = useState<IWebBid | null>(null);

  const { setConfirm } = useConfirmStore();

  const [webBidOpened, webBidModal] = useDisclosure(false);
  const [webAccountOpened, webAccountModal] = useDisclosure(false);
  const [scrapConfigOpened, scrapConfigModal] = useDisclosure(false);

  const columns: IColumn<IWebBid>[] = [
    {
      key: "id",
      title: "ID",
      typeFilter: "number",
    },
    {
      key: "origin_url",
      title: "Domain",
      typeFilter: "text",
    },
    {
      key: "url",
      title: "Tracking url",
      typeFilter: "text",
      renderRow(row) {
        return <Text>{row.url || "None"}</Text>;
      },
    },
    {
      key: "active",
      title: "Status",
      typeFilter: "text",
      renderRow(row) {
        return (
          <Box className="flex items-center justify-center">
            <Badge color={row.active ? "green" : "red"} size="sm">
              {row.active ? "Enable" : "Disable"}
            </Badge>
          </Box>
        );
      },
    },

    {
      key: "created_at",
      title: "Created at",
      typeFilter: "none",
      renderRow(row) {
        return <span>{formatTime(row.created_at)}</span>;
      },
    },
    {
      key: "updated_at",
      title: "Update at",
      typeFilter: "none",
      renderRow(row) {
        return <span>{formatTime(row.updated_at)}</span>;
      },
    },
  ];

  const handleDelete = (data: IWebBid) => {
    setConfirm({
      title: "Delete ?",
      message: "This web will be delete",
      handleOk: async () => {
        await deleteWebBid(data);

        if (refTableFn.current?.fetchData) {
          refTableFn.current.fetchData();
        }
      },
    });
  };

  const handleToggle = async (data: IWebBid) => {
    setConfirm({
      title: (data.active ? "Disable " : "Enable ") + "ID: " + data.id,
      message: "This web will be " + (data.active ? "disable " : "enable "),
      handleOk: async () => {
        await updateWebBid({ ...data, active: !data.active || false });

        if (refTableFn.current?.fetchData) {
          refTableFn.current.fetchData();
        }
      },
      okButton: {
        value: data.active ? "Disable " : "Enable ",
        color: data.active ? "red" : "blue",
      },
    });
  };

  const table = useMemo(() => {
    return (
      <Table
        actionsOptions={{
          actions: [
            {
              key: "add",
              title: "Add",
              callback: () => {
                webBidModal.open();
              },
            },
            {
              key: "delete",
              title: "Delete",
              callback: (data) => {
                if (!data.length) return;
                setConfirm({
                  title: "Delete",
                  message: `${data.length} will be delete`,
                  handleOk: async () => {
                    const result = await deletesWebBid(data);

                    if (!result) return;
                    if (refTableFn.current.fetchData) {
                      refTableFn.current.fetchData();
                    }
                  },
                });
              },
              disabled: (data) => data.length <= 0,
            },
          ],
        }}
        refTableFn={refTableFn}
        striped
        showLoading={true}
        highlightOnHover
        styleDefaultHead={{
          justifyContent: "flex-start",
          width: "fit-content",
        }}
        options={{
          query: getWebBids,
          pathToData: "data.data",
          keyOptions: {
            last_page: "lastPage",
            per_page: "perPage",
            from: "from",
            to: "to",
            total: "total",
          },
        }}
        rows={[]}
        withColumnBorders
        showChooses={true}
        withTableBorder
        columns={columns}
        actions={{
          title: <Box className="w-full text-center">Action</Box>,
          body: (row) => {
            return (
              <Menu shadow="md" width={200}>
                <Menu.Target>
                  <Box className="flex w-full items-center justify-center">
                    <ActionIcon size="sm" variant="light">
                      <IconMenu size={14} />
                    </ActionIcon>
                  </Box>
                </Menu.Target>

                <Menu.Dropdown>
                  <Menu.Item
                    onClick={() => {
                      setClickData(row);
                      webBidModal.open();
                    }}
                    leftSection={<IconEdit size={14} />}
                  >
                    Edit
                  </Menu.Item>
                  <Menu.Item
                    onClick={() => {
                      setClickData(row);
                      webAccountModal.open();
                    }}
                    leftSection={<IconUserEdit size={14} />}
                  >
                    Account
                  </Menu.Item>

                  <Menu.Item
                    onClick={() => {
                      setClickData(row);
                      scrapConfigModal.open();
                    }}
                    leftSection={<IconSettingsCode size={14} />}
                  >
                    Scrap config
                  </Menu.Item>

                  <Menu.Item
                    onClick={() => handleToggle(row)}
                    leftSection={
                      row.active ? (
                        <IconAdOff size={14} />
                      ) : (
                        <IconAd size={14} />
                      )
                    }
                  >
                    {row.active ? "Disable" : "Enable"}
                  </Menu.Item>

                  <Menu.Item
                    onClick={() => handleDelete(row)}
                    leftSection={<IconTrash color="red" size={14} />}
                  >
                    Delete
                  </Menu.Item>
                </Menu.Dropdown>
              </Menu>
            );
          },
        }}
        rowKey="id"
      />
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <Box>
      {table}

      <WebBidModal
        data={clickData}
        opened={webBidOpened}
        onClose={() => {
          webBidModal.close();
          setClickData(null);
        }}
        onUpdated={() => {
          setClickData(null);

          if (refTableFn.current?.fetchData) {
            refTableFn.current.fetchData();
          }
        }}
      />

      <WebAccountModal
        data={clickData}
        opened={webAccountOpened}
        onClose={() => {
          webAccountModal.close();
          setClickData(null);
        }}
        onUpdated={() => {
          setClickData(null);

          if (refTableFn.current?.fetchData) {
            refTableFn.current.fetchData();
          }
        }}
      />

      <ScrapConfigModal
        data={clickData}
        opened={scrapConfigOpened}
        onClose={() => {
          scrapConfigModal.close();
          setClickData(null);
        }}
        onUpdated={() => {
          setClickData(null);

          if (refTableFn.current?.fetchData) {
            refTableFn.current.fetchData();
          }
        }}
      />
    </Box>
  );
}
