import { useEffect, useState } from "react";
import { Grid } from "../components/Grid/Grid";
import Table from "../components/Table/Table";
import { useApiRequest } from "../utils/useApiRequest";
import { Popover } from "../components/PopOver/PopOver";
import { Tooltip } from "../components/Tooltip/Tooltip";
import Button from "../components/Button/Button";
import { useNavigate } from "@tanstack/react-router";
import { POS_COMPANIES } from "../routes/paths";

export default function PosCompanies() {
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [pagesTableData, setPagesTableData] = useState([]);

  const navigate = useNavigate();
  const { data: pagesData } = useApiRequest({
    api: "/pos_device/web/v1/pos/device/psp_organizations/",
    method: "get",
    params: { pagesInfo },
    queryKey: ["posCompanies", 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?.name,
          item?.national_unique_id,
          item?.province
            ? `${item?.province?.name} (${item?.city?.name})`
            : "-",
          item?.field_of_activity === "CO"
            ? "کشور"
            : item?.field_of_activity === "PR"
            ? "استان"
            : item?.field_of_activity === "CI"
            ? "شهرستان"
            : "نامشخص",
          <Popover key={i}>
            <Tooltip title="نمایش کارتخوان ها" position="right">
              <Button
                page="pos_company_detail"
                access="Show-Pos-Company-Devices"
                variant="detail"
                onClick={() => {
                  const path =
                    POS_COMPANIES + "/" + item?.id + "/" + item?.name;
                  navigate({ to: path });
                }}
              />
            </Tooltip>
          </Popover>,
        ];
      });
      setPagesTableData(formattedData);
    }
  }, [pagesData, pagesInfo]);

  return (
    <Grid container column>
      <Table
        className="mt-2"
        onChange={setPagesInfo}
        count={pagesData?.count || 10}
        isPaginated
        title="شرکت های پرداخت"
        columns={[
          "ردیف",
          "نام",
          "شناسه یکتا",
          "استان/شهر",
          "حوزه فعالیت",
          "عملیات",
        ]}
        rows={pagesTableData}
      />
    </Grid>
  );
}
