import { useEffect, useMemo, useState } from "react";
import {
  MaterialReactTable,
  useMaterialReactTable,
} from "material-react-table";
import { MRT_Localization_FA } from "material-react-table/locales/fa";
import { Grid } from "../grid/Grid";
import { useSelector } from "react-redux";
import { formatJustDate } from "../../utils/formatTime";
import axios from "axios";
import { Box } from "@mui/material";
import { RowItemCity } from "./RowItemCity";

export const FlexTable = () => {
  const { authToken } = useSelector((state) => state.userSlice);
  const [data, setData] = useState([]);
  const [isError, setIsError] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isRefetching, setIsRefetching] = useState(false);
  const [rowCount, setRowCount] = useState(0);

  const [columnFilters, setColumnFilters] = useState([]);
  const [globalFilter, setGlobalFilter] = useState("");
  const [sorting, setSorting] = useState([]);
  const [pagination, setPagination] = useState({
    pageIndex: 0,
    pageSize: 10,
  });

  useEffect(() => {
    const fetchData = async () => {
      if (!data.length) {
        setIsLoading(true);
      } else {
        setIsRefetching(true);
      }
      const url = new URL(
        `${axios.defaults.baseURL}poultry_requests_for_total_information_in_table/?date1=2023-12-24&date2=2023-12-26&search=filter&value=`
      );
      // url.searchParams.set(
      //   "page",
      //   `${pagination.pageIndex * pagination.pageSize}`
      // );

      url.searchParams.set("page", `${pagination.pageIndex + 1}`);
      url.searchParams.set("size", `${pagination.pageSize}`);
      url.searchParams.set("filters", JSON.stringify(columnFilters ?? []));
      url.searchParams.set("globalFilter", globalFilter ?? "");
      url.searchParams.set("sorting", JSON.stringify(sorting ?? []));

      try {
        const response = await fetch(url.href, {
          headers: {
            Authorization: `Bearer ${authToken}`,
          },
        });
        const json = await response.json();
        const refineData = json.results.map((item) => {
          let sellType = "";

          if (item.directBuying) {
            sellType = "خرید مستقیم";
          } else if (item.union) {
            sellType = "خرید خارج از استان";
          } else {
            sellType = "اتحادیه";
          }
          return {
            shomarehParvande: item?.order_code,
            tarikhKoshtar: formatJustDate(item?.send_date),
            noeForoosh: sellType,
            farmMorghdar: item?.poultry?.unit_name,
            tedad: item?.quantity?.toLocaleString(),
            vaznTotal: (item?.quantity * item?.Index_weight)?.toLocaleString(),
            ghimatMorghdar: item?.amount?.toLocaleString() + " ریال",
            item,
          };
        });
        setData(refineData);
        setRowCount(json.count);
      } catch (error) {
        setIsError(true);
        console.error(error);
        return;
      }
      setIsError(false);
      setIsLoading(false);
      setIsRefetching(false);
    };
    fetchData();
  }, [
    columnFilters,
    globalFilter,
    pagination.pageIndex,
    pagination.pageSize,
    sorting,
  ]);

  const columns = useMemo(
    () => [
      {
        accessorKey: "shomarehParvande",
        header: "شماره پرونده",
      },
      {
        accessorKey: "tarikhKoshtar",
        header: "تاریخ کشتار",
      },
      {
        accessorKey: "noeForoosh",
        header: "نوع فروش",
      },
      {
        accessorKey: "farmMorghdar",
        header: "فارم (مرغدار)",
      },
      {
        accessorKey: "tedad",
        header: "تعداد",
      },
      {
        accessorKey: "vaznTotal",
        header: "وزن کل (کیلوگرم)",
      },
      {
        accessorKey: "ghimatMorghdar",
        header: "قیمت مرغدار",
      },
    ],
    []
  );

  const table = useMaterialReactTable({
    columns,
    data,
    renderDetailPanel: ({ row }) => {
      return (
        <Box
          sx={{
            // display: "grid",
            margin: "auto",
            // gridTemplateColumns: "1fr 1fr",
            width: "100%",
          }}
        >
          <RowItemCity item={row.original.item} />
          {/* <Typography>Address</Typography> */}
          {/* <Typography>City: {row.original.city}</Typography>
        <Typography>State: {row.original.state}</Typography>
        <Typography>Country: {row.original.country}</Typography> */}
        </Box>
      );
    },
    enableRowSelection: true,
    getRowId: (row) => row.key,
    initialState: {
      showColumnFilters: true,
      density: "compact",
      enableRowOrdering: false,
    },
    manualFiltering: true,
    manualPagination: true,
    enableStickyHeader: true,
    manualSorting: true,
    muiToolbarAlertBannerProps: isError
      ? {
          color: "error",
          children: "مشکلی پیش آمده است.",
        }
      : undefined,
    onColumnFiltersChange: setColumnFilters,
    onGlobalFilterChange: setGlobalFilter,
    onPaginationChange: setPagination,
    onSortingChange: setSorting,
    rowCount,
    state: {
      columnFilters,
      globalFilter,
      isLoading,
      pagination,
      showAlertBanner: isError,
      showProgressBars: isRefetching,
      sorting,
    },
    enableColumnOrdering: true,
    localization: MRT_Localization_FA,
  });

  return (
    <Grid xs={9}>
      <MaterialReactTable table={table} />
    </Grid>
  );
};
