import React, { useEffect, useState } from "react";
import { useApiRequest } from "../../utils/useApiRequest";
import { Grid } from "../../components/Grid/Grid";
import Table from "../../components/Table/Table";
import ShowMoreInfo from "../../components/ShowMoreInfo/ShowMoreInfo";
import ShowStringList from "../../components/ShowStringList/ShowStringList";
import { AddActivityTypeSettings } from "./AddActivityTypeSettings";

type SettingsType = "purchase_policy" | "service_area";

type CooperativesSettingsTableProps = {
  settingsType: SettingsType;
};

export const CooperativesSettingsTable = ({
  settingsType,
}: CooperativesSettingsTableProps) => {
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [cooperativesTableData, setCooperativesTableData] = useState([]);

  const { data: cooperativesData, refetch } = useApiRequest({
    api: "herd/web/api/v1/rancher_org_link/org_linked_rancher_list",
    method: "get",
    params: {
      ...pagesInfo,
    },
    queryKey: ["cooperatives-settings", pagesInfo],
  });

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

  useEffect(() => {
    if (cooperativesData?.results) {
      const formattedData = cooperativesData.results.map(
        (item: any, i: number) => {
          const baseColumns = [
            pagesInfo.page === 1
              ? i + 1
              : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
            item?.name || "-",
            item?.province || "-",
            item?.city || "-",
            item?.rancher_count || 0,
            item?.herd_count || 0,
            item?.livestock_count || 0,
          ];

          let lastColumn: React.ReactNode;

          if (settingsType === "service_area") {
            lastColumn = item?.org_service_area?.length ? (
              <ShowMoreInfo key={i} title="محدوده فعالیت">
                <Grid
                  container
                  column
                  className="gap-2 p-2 justify-start items-start w-full"
                >
                  <ShowStringList
                    showSearch={false}
                    strings={item.org_service_area.map(
                      (city: any) => city.name
                    )}
                  />
                </Grid>
              </ShowMoreInfo>
            ) : (
              "-"
            );
          } else {
            lastColumn =
              item?.org_purchase_policy === "INTERNAL_ONLY"
                ? "بر اساس تعاونی"
                : item?.org_purchase_policy === "CROSS_COOP"
                ? "برای کل استان"
                : "-";
          }

          // Add editable component
          const editableColumn = (
            <AddActivityTypeSettings
              key={i}
              item={item}
              settingsType={settingsType}
              onUpdate={handleUpdate}
            />
          );

          return [...baseColumns, lastColumn, editableColumn];
        }
      );
      setCooperativesTableData(formattedData);
    }
  }, [cooperativesData, pagesInfo, settingsType]);

  const getColumns = () => {
    const baseColumns = [
      "ردیف",
      "نام",
      "استان",
      "شهر",
      "تعداد دامدار",
      "تعداد گله",
      "تعداد دام",
    ];

    if (settingsType === "service_area") {
      return [...baseColumns, "محدوده فعالیت", "ویرایش محدوده فعالیت"];
    } else {
      return [...baseColumns, "محدودیت دریافت نهاده", "ویرایش محدودیت"];
    }
  };

  return (
    <Grid container column className="gap-4 mt-2">
      <Table
        className="mt-2"
        onChange={(e) => {
          setPagesInfo(e);
        }}
        count={cooperativesData?.count || 10}
        isPaginated
        title={
          settingsType === "service_area"
            ? "محدوده فعالیت تعاونی ها"
            : "محدودیت دریافت نهاده تعاونی ها"
        }
        columns={getColumns()}
        rows={cooperativesTableData}
      />
    </Grid>
  );
};
