import { useEffect, useState } from "react";
import { Grid } from "../../components/Grid/Grid";
import Button from "../../components/Button/Button";
import { AddOrganization } from "./AddOrganization";
import AutoComplete from "../../components/AutoComplete/AutoComplete";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";
import Table from "../../components/Table/Table";
import { useModalStore } from "../../context/zustand-store/appStore";
import { useApiRequest } from "../../utils/useApiRequest";
import { DeleteButtonForPopOver } from "../../components/PopOverButtons/PopOverButtons";
import { Tooltip } from "../../components/Tooltip/Tooltip";
import { Popover } from "../../components/PopOver/PopOver";
import { AddCard } from "./AddCard";
import ShowMoreInfo from "../../components/ShowMoreInfo/ShowMoreInfo";
import { ShowCardsStringList } from "../../components/ShowCardsStringList/ShowCardsStringList";
import { useUserProfileStore } from "../../context/zustand-store/userStore";

export const OrganizationsList = () => {
  const { openModal } = useModalStore();
  const [selectedProvinceKeys, setSelectedProvinceKeys] = useState<
    (string | number)[]
  >([]);
  const [selectedOrganizationType, setSelectedOrganizationType] = useState<
    string | number
  >("");
  const [params, setParams] = useState({ page: 1, page_size: 10 });
  const [tableData, setTableData] = useState([]);
  const { profile } = useUserProfileStore();

  const { data: provinceData } = useApiRequest({
    api: "/auth/api/v1/province/",
    method: "get",
    params: { page: 1, page_size: 1000 },
    queryKey: ["provinces"],
  });

  const { data: apiData, refetch } = useApiRequest({
    api: selectedProvinceKeys?.length
      ? `/auth/api/v1/organization/organizations_by_province?province=${selectedProvinceKeys[0]}${selectedOrganizationType ? `&org_type=${selectedOrganizationType}` : ""}`
      : `/auth/api/v1/organization/${selectedOrganizationType ? `?org_type=${selectedOrganizationType}` : ""}`,
    method: "get",
    params: params,
    queryKey: [
      "organizations",
      params,
      selectedProvinceKeys,
      selectedOrganizationType,
    ],
  });

  useEffect(() => {
    if (apiData?.results) {
      const formattedData = apiData.results.map((item: any, i: number) => {
        return [
          params.page === 1
            ? i + 1
            : i + params.page_size * (params.page - 1) + 1,
          item?.name,
          `${item?.type?.name}`,
          item?.parent_organization?.name,
          item?.national_unique_id,
          item?.unique_unit_identity || "-",
          item?.field_of_activity === "CO"
            ? "کشور"
            : item?.field_of_activity === "PR"
              ? "استان"
              : item?.field_of_activity === "CI"
                ? "شهرستان"
                : "نامشخص",
          item?.province?.name,
          item?.city?.name,
          <ShowMoreInfo
            key={`address-${i}`}
            title="آدرس‌ها"
            disabled={!item?.addresses?.length}
            data={item?.addresses}
            columns={["کد پستی", "آدرس"]}
            accessKeys={[["postal_code"], ["address"]]}
          />,
          <ShowMoreInfo
            key={i}
            title="اطلاعات حساب"
            disabled={
              item?.bank_account?.length ? !item?.bank_account.length : true
            }
          >
            <ShowCardsStringList
              fields={[
                { label: "بانک", value: item?.bank_account?.[0]?.name },
                { label: "شماره کارت", value: item?.bank_account?.[0]?.card },
                {
                  label: "شماره حساب",
                  value: item?.bank_account?.[0]?.account,
                },
                { label: "شماره شبا", value: item?.bank_account?.[0]?.sheba },
              ]}
            />
          </ShowMoreInfo>,
          <Popover key={i}>
            <Tooltip title="ویرایش سازمان" position="right">
              <Button
                page="organizations"
                access="Update-Organization"
                variant="edit"
                onClick={() => {
                  openModal({
                    title: "ویرایش سازمان",
                    content: <AddOrganization getData={refetch} item={item} />,
                  });
                }}
              />
            </Tooltip>
            <Tooltip title="تعریف حساب" position="right">
              <Button
                page="organizations"
                access="Add-Card"
                variant="submit"
                onClick={() => {
                  openModal({
                    title: "تعریف حساب",
                    content: (
                      <AddCard
                        getData={refetch}
                        item={item}
                        target={item?.name}
                      />
                    ),
                  });
                }}
              />
            </Tooltip>
            <DeleteButtonForPopOver
              page="organizations"
              access="Delete-Organization"
              title="از حذف سازمان اطمینان دارید؟"
              api={`/auth/api/v1/organization/${item?.id}/`}
              getData={refetch}
            />
          </Popover>,
        ];
      });
      setTableData(formattedData);
    }
  }, [apiData, params]);

  const formattedProvinceData =
    provinceData?.results?.map((province: any) => ({
      key: province.id,
      value: province.name,
    })) || [];

  return (
    <>
      <Grid container className="items-center gap-2">
        <Grid>
          <Button
            size="small"
            page="organizations"
            access="Create-Organization"
            variant="submit"
            onClick={() =>
              openModal({
                title: "ایجاد سازمان",
                content: <AddOrganization getData={refetch} />,
              })
            }
          >
            ایجاد سازمان
          </Button>
        </Grid>
        <Grid>
          <FormApiBasedAutoComplete
            size="small"
            title="فیلتر نهاد"
            api={`auth/api/v1/organization-type`}
            keyField="id"
            valueField="name"
            onChange={(r) => setSelectedOrganizationType(r)}
          />
        </Grid>
        {profile?.organization?.type?.org_type_field === "CO" && (
          <Grid>
            <AutoComplete
              inPage
              size="small"
              data={formattedProvinceData}
              selectedKeys={selectedProvinceKeys}
              onChange={setSelectedProvinceKeys}
              title="فیلتر استان"
            />
          </Grid>
        )}
      </Grid>
      <Grid className="w-full">
        <Table
          className="mt-2"
          onChange={setParams}
          title="سازمان ها"
          isPaginated
          count={apiData?.count || 10}
          columns={[
            "ردیف",
            "نام سازمان",
            "نهاد",
            "سازمان والد",
            "شناسه کشوری",
            "شناسه یکتا واحد",
            "حوزه فعالیت",
            "استان",
            "شهر",
            "آدرس",
            "اطلاعات حساب",
            "عملیات",
          ]}
          rows={tableData}
        />
      </Grid>
    </>
  );
};
