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

interface ChildOrganizationsProps {
  orgId: number;
  orgName: string;
}

export const ChildOrganizations: React.FC<ChildOrganizationsProps> = ({
  orgId,
  orgName,
}) => {
  const [pagesInfo, setPagesInfo] = useState({ page: 1, page_size: 10 });
  const [childOrgsTableData, setChildOrgsTableData] = useState([]);

  const { data: childOrgsData } = useApiRequest({
    api: `/auth/api/v1/organization/child_organizations?org_id=${orgId}`,
    method: "get",
    params: {
      ...pagesInfo,
    },
    queryKey: ["childOrganizations", orgId, pagesInfo],
  });

  useEffect(() => {
    if (childOrgsData?.results) {
      const formattedData = childOrgsData.results.map(
        (item: any, i: number) => {
          return [
            pagesInfo.page === 1
              ? i + 1
              : i + pagesInfo.page_size * (pagesInfo.page - 1) + 1,
            item?.name || "-",
            item?.type?.name || "-",
            item?.province?.name || "-",
            item?.city?.name || "-",
            item?.parent_organization?.name || "-",
            item?.national_unique_id || "-",
            item?.address || "-",
          ];
        }
      );
      setChildOrgsTableData(formattedData);
    }
  }, [childOrgsData, pagesInfo]);

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