import { useEffect, useState } from "react";
import { useApiRequest } from "../utils/useApiRequest";
import { Grid } from "../components/Grid/Grid";
import Table from "../components/Table/Table";
import Button from "../components/Button/Button";
import { useModalStore } from "../context/zustand-store/appStore";
import { AddPos } from "../partials/pos/AddPos";
import { Popover } from "../components/PopOver/PopOver";
import { Tooltip } from "../components/Tooltip/Tooltip";
import { DeleteButtonForPopOver } from "../components/PopOverButtons/PopOverButtons";
import { useUserProfileStore } from "../context/zustand-store/userStore";
import { useNavigate, useParams } from "@tanstack/react-router";
import { AllocatePos } from "../partials/pos/AllocatePos";
import { CreditCardIcon } from "@heroicons/react/24/outline";
import { POS_POS_LIST } from "../routes/paths";

export default function Pos() {
  const { openModal } = useModalStore();
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);
  const { profile } = useUserProfileStore();
  const { id, name } = useParams({ strict: false });
  const navigate = useNavigate();

  const { data: pagesData, refetch } = useApiRequest({
    api: id
      ? `pos_device/web/v1/pos/device/${id}/devices_by_psp/`
      : "/pos_device/web/v1/pos/device/my_devices/",
    method: "get",
    params: {
      ...pagesInfo,
      admin: profile?.role?.type?.key === "ADM" ? true : false,
    },
    queryKey: ["pos", pagesInfo],
  });

  useEffect(() => {
    if (pagesData?.results) {
      const formattedData = pagesData.results.map((item: any, i: number) => {
        return [
          pagesInfo.page === 1
            ? i + 1
            : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
          item?.assignment?.client
            ? `${
                item?.assignment?.client?.organization?.id ? "سازمان" : "صنف"
              } ${item?.assignment?.client?.organization?.name}`
            : "-",
          item?.organization?.name,
          item?.acceptor,
          item?.serial,
          item?.terminal,
          item?.device_identity,
          item?.is_activated ? "فعال" : "غیر فعال",
          <Popover key={i}>
            <Tooltip title={"تعریف حساب"} position="right">
              <Button
                icon={<CreditCardIcon className="w-5 h-5 text-secondary-600" />}
                page={"pos_accounts"}
                access="Pos-Accounts"
                onClick={() => {
                  const path = POS_POS_LIST + "/" + item?.id;
                  navigate({ to: path });
                }}
              />
            </Tooltip>
            <Tooltip
              title={
                item?.assignment?.client
                  ? "ویرایش تخصیص سازمان"
                  : "تخصیص سازمان"
              }
              position="right"
            >
              <Button
                variant={item?.assignment?.client ? "secondary-edit" : "submit"}
                page={"pos"}
                access="Pos-Allocate-Organization"
                onClick={() => {
                  openModal({
                    title: item?.assignment?.client
                      ? "ویرایش تخصیص سازمان"
                      : "تخصیص سازمان",
                    content: <AllocatePos getData={refetch} item={item} />,
                  });
                }}
              />
            </Tooltip>
            <Tooltip title="ویرایش" position="right">
              <Button
                page={name ? "pos_company_detail" : "pos"}
                access="Edit-Pos"
                variant="edit"
                onClick={() => {
                  openModal({
                    title: "ویرایش کارتخوان",
                    content: <AddPos getData={refetch} item={item} />,
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page={name ? "pos_company_detail" : "pos"}
              access="Delete-Pos-Device"
              api={`pos_device/web/v1/pos/device/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setPagesTableData(formattedData);
    }
  }, [pagesData, pagesInfo]);

  return (
    <Grid container column>
      {!id && (
        <Grid>
          <Button
            size="small"
            variant="submit"
            page="pos"
            access="Submit-Pos-Device"
            onClick={() => {
              openModal({
                title: "ثبت کارتخوان",
                content: <AddPos getData={refetch} />,
              });
            }}
          >
            ثبت کارتخوان
          </Button>
        </Grid>
      )}
      <Table
        className="mt-2"
        onChange={setPagesInfo}
        count={pagesData?.count || 10}
        isPaginated
        title={`دستگاه های ${name ? name : "پرداخت"} `}
        columns={[
          "ردیف",
          "مالک",
          "شرکت psp",
          "پذیرنده",
          "سریال",
          "ترمینال",
          "کد پشتیبانی",
          "وضعیت",
          "عملیات",
        ]}
        rows={pagesTableData}
      />
    </Grid>
  );
}
