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 { useParams } from "@tanstack/react-router";
import { AllocatePos } from "../partials/pos/AllocatePos";
import { PosAllocateOrganizationAccount } from "../partials/pos/PosAllocateOrganizationAccount";
import { AllocateAccountToBroker } from "../partials/pos/AllocateAccountToBroker";
import { BooleanQuestion } from "../components/BooleanQuestion/BooleanQuestion";

export default function PosAccounts() {
  const { openModal } = useModalStore();
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [accountsTableData, setAccountsTableData] = useState([]);

  const { id } = useParams({ strict: false });

  const { data: posData, refetch } = useApiRequest({
    api: `/pos_device/web/v1/pos/device/${id}/`,
    method: "get",
    queryKey: ["posAccountsDashboard", pagesInfo],
  });

  const { data: posAccountsData, refetch: accountsRefetch } = useApiRequest({
    api: `pos_device/web/v1/pos/stake_holders/${id}/list_by_device/`,
    method: "get",
    params: {
      ...pagesInfo,
    },
    queryKey: ["posAccounts", pagesInfo],
  });

  useEffect(() => {
    if (posAccountsData?.results) {
      const formattedData = posAccountsData.results.map(
        (item: any, i: number) => {
          return [
            pagesInfo.page === 1
              ? i + 1
              : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
            item?.organization?.name,
            item?.bank_account?.card,
            item?.bank_account?.account,
            item?.bank_account?.sheba,
            item?.default ? "حساب اصلی" : "زیر حساب",
            item?.broker?.name,
            <Popover key={i}>
              <Tooltip title={"تخصیص به کارگزار"} position="right">
                <Button
                  page="pos_accounts"
                  access="Allocate-Account-To-Broker"
                  variant="submit"
                  onClick={() => {
                    openModal({
                      title: "تخصیص به کارگزار",
                      content: (
                        <AllocateAccountToBroker
                          getData={accountsRefetch}
                          item={item}
                        />
                      ),
                    });
                  }}
                />
              </Tooltip>
              <Tooltip title={"تنظیم بعنوان حساب اصلی"} position="right">
                <Button
                  page="pos_accounts"
                  access="Set-Main-Account"
                  variant="set"
                  onClick={() => {
                    openModal({
                      title: "تنظیم بعنوان حساب اصلی",
                      content: (
                        <BooleanQuestion
                          api="pos_device/web/v1/pos/bank_account_device_link"
                          method="post"
                          getData={handleUpdate}
                          title="آیا از تنظیم این حساب بعنوان حساب اصلی مطمئنید؟"
                          payload={{
                            organization: posData?.organization?.id,
                            bank_account: item?.bank_account?.id,
                            device: item?.id,
                          }}
                        />
                      ),
                    });
                  }}
                />
              </Tooltip>
              <DeleteButtonForPopOver
                page="pos_accounts"
                access="Delete-Account"
                api={`pos_device/web/v1/pos/stake_holders/${item?.id}/`}
                getData={handleUpdate}
              />
            </Popover>,
          ];
        }
      );
      setAccountsTableData(formattedData);
    }
  }, [posAccountsData, pagesInfo]);

  const handleUpdate = () => {
    refetch();
    accountsRefetch();
  };

  return (
    <Grid container column>
      <Grid container column isDashboard>
        <Table
          noPagination
          isDashboard
          className="mt-2"
          onChange={setPagesInfo}
          count={posData?.count || 10}
          isPaginated
          title={`مشخصات کارتخوان`}
          columns={[
            "مالک",
            "شرکت psp",
            "پذیرنده",
            "سریال",
            "ترمینال",
            "وضعیت",
            "عملیات",
          ]}
          rows={[
            [
              posData?.assignment?.client
                ? `${
                    posData?.assignment?.client?.organization?.id
                      ? "سازمان"
                      : "صنف"
                  } ${posData?.assignment?.client?.organization?.name}`
                : "-",
              posData?.organization?.name,
              posData?.acceptor,
              posData?.serial,
              posData?.terminal,
              posData?.is_activated ? "فعال" : "غیر فعال",
              <Popover key={posData}>
                <Tooltip
                  title={
                    posData?.assignment?.client
                      ? "ویرایش تخصیص"
                      : "تخصیص سازمان"
                  }
                  position="right"
                >
                  <Button
                    variant="submit"
                    page="pos_accounts"
                    access="Allocate-Pos-Account"
                    onClick={() => {
                      openModal({
                        title: posData?.assignment?.client
                          ? "ویرایش سازمان"
                          : "تخصیص سازمان",
                        content: (
                          <AllocatePos getData={handleUpdate} item={posData} />
                        ),
                      });
                    }}
                  />
                </Tooltip>
                <Tooltip title="ویرایش" position="right">
                  <Button
                    variant="edit"
                    page="pos_accounts"
                    access="Edit-Pos-Account"
                    onClick={() => {
                      openModal({
                        title: "ویرایش کارتخوان",
                        content: (
                          <AddPos getData={handleUpdate} item={posData} />
                        ),
                      });
                    }}
                  />
                </Tooltip>
                <DeleteButtonForPopOver
                  page="pos_accounts"
                  access="Delete-Pos"
                  api={`pos_device/web/v1/pos/device/${posData?.id}/`}
                  getData={handleUpdate}
                />
              </Popover>,
            ],
          ]}
        />
      </Grid>

      <Grid className="mt-16" container column>
        <Grid>
          <Button
            size="small"
            variant="submit"
            page="pos_accounts"
            access="Allocate-Account"
            onClick={() => {
              openModal({
                title: "انتخاب لیست زیر حساب",
                content: (
                  <PosAllocateOrganizationAccount
                    getData={handleUpdate}
                    item={posData}
                    deviceId={id}
                  />
                ),
              });
            }}
          >
            انتخاب لیست زیر حساب
          </Button>
        </Grid>
        <Table
          className="mt-8"
          onChange={setPagesInfo}
          count={posAccountsData?.count || 10}
          isPaginated
          title={`زیر حساب ها`}
          columns={[
            "ردیف",
            "سازمان",
            "شماره کارت",
            "شماره حساب",
            "شماره شبا",
            "نوع",
            "کارگزار",
            "عملیات",
          ]}
          rows={accountsTableData}
        />
      </Grid>
    </Grid>
  );
}
