import {
  Box,
  Button,
  // FormControl,
  // InputLabel,
  // MenuItem,
  // Select,
  // TextField,
  Tab,
  Tabs,
  // Tooltip,
  // Typography,
} from "@mui/material";
import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
// import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable";
// import { ExcelUploadButton } from "../../../../components/excel-upload-button/ExcelUploadButton";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice";
// import { formatJustDate } from "../../../../utils/formatTime";
// import { cityGetHatchings } from "../../services/city-get-hatchings";
// import { getSlaughtersKillRequestService } from "../../services/get-slaughters-kill-request";
// import { avicultureHatchingRequestsService } from "../../../aviculture/services/aviculture-hatching-requests";
import { useFormik } from "formik";
// import { RiFileExcel2Fill } from "react-icons/ri";
// import axios from "axios";
// import { DatePicker } from "@mui/x-date-pickers";
// import moment from "moment/moment";
// import { CityManageHatchingsOperations } from "../city-manage-hatchings-operations/CityManageHatchingsOperations";
// import { cityGetHatchingsByAge } from "../../services/city-get-hatchings-by-age";
// import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { CityArchiveOldHatchings } from "../city-archive-old-hatchings/CityArchvieOldHatchings";
import { cityGetArchiveHatchingsService } from "../../services/city-get-archive-hatchings";
import { CityHatchings } from "../city-hatchings/CityHatchings";
import { CityHatchingsArchive } from "../city-hatchings-archive/CityHatchingsArchive";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { CityHatchingInfo } from "../city-hatching-info/CityHatchingInfo";
import { CityUpdateHatching } from "../city-update-hatching/CityUpdateHatching";
import { ProvinceBarDifference } from "../../../province/components/province-bar-difference/ProvinceBarDifference";
import { TransportChickens } from "../transport-chickens/TransportChickens";
import { CityHatchingsTotal } from "../city-hatchings-total/CityHatchingsTotal";
import { CityHatchingUnassigned } from "../city-hatching-unassigned/CityHatchingUnassigned";

export const CityManageHatchings = () => {
  const dispatch = useDispatch();
  const [, , selectedDate1, , selectedDate2] = useContext(AppContext);
  // const [dataTable, setDataTable] = useState([]);

  // const [searchClick, setSearchClick] = useState(true);

  // const [dataTableHatchingArchive, setDataTableHatchingArchive] = useState([]);
  // const [selectedAge1, setSelectedAge1] = useState(45);
  // const [selectedAge2, setSelectedAge2] = useState(75);

  // const [filterType, setFilterType] = useState("سن");

  const formik = useFormik({
    initialValues: {
      numberInput: 0,
    },
  });

  const { hatchings, poultryRequestsTotalQuantity, cityGetArchiveHatchings } =
    useSelector((state) => state.citySlice);

  // const { hourLimitKillRequest } = useSelector((state) => state.citySlice);
  const { getSlaughtersKillRequest } = useSelector((state) => state.citySlice);

  // useEffect(() => {
  //   dispatch(getSlaughtersKillRequestService());
  //   dispatch(
  //     avicultureHatchingRequestsService({ selectedDate1, selectedDate2 })
  //   );
  // }, [selectedDate1, selectedDate2]);

  // useEffect(() => {
  //   const past50Day = new Date();
  //   past50Day.setDate(past50Day.getDate() - 45);
  //   setSelectedDate1(moment(past50Day).format("YYYY-MM-DD"));
  //   return () => {
  //     const date = new Date();
  //     setSelectedDate1(moment(date).format("YYYY-MM-DD"));
  //   };
  // }, []);

  // useEffect(() => {
  //   dispatch(cityGetHatchings({ selectedDate1, selectedDate2 }));
  // }, [searchClick]);

  // useEffect(() => {
  //   if (searchClick) {
  //     dispatch(cityGetHatchings({ selectedDate1, selectedDate2 }));
  //     setSearchClick(false);
  //   }
  // }, [selectedDate1]);

  useEffect(() => {
    if (poultryRequestsTotalQuantity) {
      formik.setFieldValue(
        "numberInput",
        poultryRequestsTotalQuantity?.quantity
      );
    }
  }, [poultryRequestsTotalQuantity]);

  useEffect(() => {
    // const d = hatchings
    //   ?.filter((item) => item.allowHatching === "pending")
    //   ?.map((item, i) => {
    //     const killedNumber = item.quantity - item.losses - item.leftOver;
    //     const lastChange =
    //       item.lastChange &&
    //       `${item.lastChange.fullName} (${getFaUserRole(
    //         item.lastChange.role
    //       )}) در تاریخ ${formatJustDate(item.lastChange.date)}`;
    //     return [
    //       i + 1,
    //       item.poultry.unitName,
    //       `${item.poultry.userprofile.fullName} (${item.poultry.userprofile.mobile})`,
    //       `${item?.poultry?.address.city.name}/${
    //         item?.poultry?.cityOperator
    //           ? item?.poultry?.cityOperator
    //           : "بدون تعاونی"
    //       }`,
    //       item?.vetFarm?.vetFarmMobile
    //         ? `${item?.vetFarm?.vetFarmFullName} (${item?.vetFarm?.vetFarmMobile})`
    //         : "-",
    //       item.hall,
    //       item.period,
    //       formatJustDate(item?.createDate),
    //       formatJustDate(item?.date),
    //       item.chickenBreed,
    //       item.age,
    //       item.quantity.toLocaleString(),
    //       `${item.losses} (%${((item.losses * 100) / item.quantity).toFixed(
    //         0
    //       )})`,
    //       killedNumber.toLocaleString() +
    //         ` (%${((killedNumber * 100) / item.quantity).toFixed(0)})`,
    //       `${item.leftOver.toLocaleString()} (%${(
    //         (item.leftOver * 100) /
    //         item.quantity
    //       ).toFixed(0)})`,
    //       item?.activeKill?.activeKill ? "دارد" : "ندارد",
    //       item?.activeKill?.countOfRequest
    //         ? item.activeKill.countOfRequest
    //         : "-",
    //       item.lastChange ? lastChange : "-",
    //       // <CityManageHatchingsOperations
    //       //   selectedAge1={selectedAge1}
    //       //   selectedAge2={selectedAge2}
    //       //   item={item}
    //       //   key={i}
    //       // />,
    //     ];
    //   });
    // setDataTable(d);
    // const hatchingArchiveData = cityGetArchiveHatchings?.map((item, i) => {
    //   const killedNumber = item.quantity - item.losses - item.leftOver;
    //   return [
    //     i + 1,
    //     item.poultry.unitName,
    //     item.poultry.userprofile.baseOrder,
    //     item.poultry.userprofile.mobile,
    //     item.hall,
    //     item.period,
    //     formatJustDate(item?.createDate),
    //     formatJustDate(item?.date),
    //     item.chickenBreed,
    //     item.age,
    //     item.quantity,
    //     `${item.losses} (%${((item.losses * 100) / item.quantity).toFixed(0)})`,
    //     killedNumber +
    //       ` (%${((killedNumber * 100) / item.quantity).toFixed(0)})`,
    //     `${item.leftOver} (%${((item.leftOver * 100) / item.quantity).toFixed(
    //       0
    //     )})`,
    //   ];
    // });
    // setDataTableHatchingArchive(hatchingArchiveData);
  }, [hatchings, getSlaughtersKillRequest, cityGetArchiveHatchings]);

  const [view, setView] = useState("active");

  const handleChange = (event, newValue) => {
    setView(newValue);
  };

  // const selectAges = Array.from({ length: 75 }, (_, i) => i + 1);

  // useEffect(() => {
  // dispatch(cityGetHatchingsByAge({ selectedAge1, selectedAge2 }));
  // }, [selectedAge1, selectedAge2]);

  useEffect(() => {
    dispatch(cityGetArchiveHatchingsService({ selectedDate1, selectedDate2 }));
  }, [selectedDate1, selectedDate2]);

  return (
    <Grid
      container
      gap={SPACING.SMALL}
      // justifyContent={{ xs: "center", lg: "space-between" }}
      alignSelf="center"
      alignItems="center"
      style={{ display: "block" }}
      // direction={{ xs: "column", lg: "row" }}
    >
      <Grid container alignItems="center" justifyContent="center">
        <Tabs
          value={view}
          onChange={handleChange}
          centered
          aria-label="hatching tabs"
          scrollButtons="auto"
          variant="scrollable"
          allowScrollButtonsMobile
          sx={{
            width: "100%",
            overflow: "hidden",
            borderBottom: "1px solid #E0E0E0",
          }}
        >
          <Tab label="جوجه ریزی های فعال" value="active" />
          <Tab label="تعیین تکلیف نشده‌ها" value="pending" />
          <Tab label="بایگانی جوجه ریزی ها" value="archive" />
          <Tab label="کل جوجه ریزی‌ها" value="total" />
          {getRoleFromUrl() !== "CityPoultry" && (
            <Tab label="گزارش فارم ها" value="info" />
          )}
          {/* {(getRoleFromUrl() === "CityOperator" ||
            getRoleFromUrl() === "ProvinceOperator" ||
            getRoleFromUrl() === "AdminX" ||
            getRoleFromUrl() === "SuperAdmin") && (
            <Tab label="اختلاف کشتار" value="bar-difference" />
          )} */}
          {/* {(getRoleFromUrl() === "AdminX" ||
            getRoleFromUrl() === "SuperAdmin") && (
            <Tab label="آپدیت جوجه ریزی" value="hatchingUpdate" />
          )} */}
          {/* {(getRoleFromUrl() === "AdminX" ||
            getRoleFromUrl() === "SuperAdmin") && (
            <Tab label="گزارش حمل مرغ زنده" value="transport-chickens" />
          )} */}
          {/* {(getRoleFromUrl() === "AdminX" ||
            getRoleFromUrl() === "SuperAdmin") && (
            <Tab label="پایش کشوری" value="national-info" />
          )}*/}
        </Tabs>
      </Grid>
      {view === "hatchingUpdate" && <CityUpdateHatching />}
      {view === "transport-chickens" && <TransportChickens />}
      {/* {view === "national-info" && <NationalInfo />} */}
      {view === "active" && (
        <Box
          container
          alignItems="center"
          justifyContent="space-between"
          // display="flex"
          style={{ width: "100%" }}
          pt={2}
        >
          <Grid
            container
            gap={SPACING.SMALL}
            justifyContent="space-between"
            mt={SPACING.TINY}
            px={{
              xs: 2,
              sm: 0,
            }}
          >
            {/* <Button
              className="first-step"
              variant={"contained"}
              disabled={true}
              onClick={() => {
                dispatch(
                  DRAWER({
                    title: "ثبت اطلاعات جوجه ریزی",
                    right: !(window.innerWidth <= 600),
                    bottom: window.innerWidth <= 600,
                    content: <CityNewHatchingRequest />,
                  })
                );
              }}
            >
              ثبت جوجه ریزی جدید
            </Button> */}
            {getRoleFromUrl() !== "CityOperator" && (
              <Button
                className="first-step"
                variant={"contained"}
                onClick={() => {
                  dispatch(
                    OPEN_MODAL({
                      title: "انتقال به بایگانی",
                      content: <CityArchiveOldHatchings />,
                    })
                  );
                }}
              >
                انتقال به بایگانی
              </Button>
            )}
          </Grid>
          {/* <ExcelUploadButton uploadUrl={""} /> */}
        </Box>
      )}
      <Grid
        alignItems={"center"}
        gap={SPACING.SMALL}
        direction={"column"}
        px={1}
      >
        <Grid container mt={SPACING.SMALL}>
          {view === "active" && <CityHatchings />}
          {view === "info" && <CityHatchingInfo />}
          {view === "bar-difference" && <ProvinceBarDifference />}
          {view === "total" && <CityHatchingsTotal />}
          {view === "pending" && <CityHatchingUnassigned />}
          {/* {view === "active" && (
            <Grid container xs={12}>
              <AdvancedTable
                name={
                  <Grid
                    container
                    alignItems="center"
                    gap={SPACING.SMALL}
                    justifyContent="space-between"
                  >
                    <Grid container alignItems="center" gap={SPACING.SMALL}>
                      <Grid>
                        <Typography fontWeight={"bold"}>
                          دوره های فعال جوجه ریزی
                        </Typography>
                      </Grid>
                      <Grid>
                        <Button
                          variant="outlined"
                          onClick={() => {
                            if (filterType === "سن") {
                              setFilterType("تاریخ");
                            } else {
                              setFilterType("سن");
                            }
                          }}
                        >
                          فیلتر جستجو
                        </Button>
                      </Grid>
                      {filterType === "سن" && (
                        <Grid container alignItems="center" gap={SPACING.SMALL}>
                          <Grid>
                            <Typography variant="caption">
                              فیلتر براساس سن:
                            </Typography>
                          </Grid>
                          <Grid style={{ width: "80px" }}>
                            <FormControl fullWidth>
                              <InputLabel id="demo-simple-select-label">
                                از سن
                              </InputLabel>
                              <Select
                                MenuProps={{
                                  PaperProps: {
                                    style: {
                                      maxHeight: 200, // Change the maximum height as needed
                                      width: 80, // Change the width as needed
                                    },
                                  },
                                }}
                                labelId="demo-simple-select-label"
                                id="demo-simple-select"
                                value={selectedAge1}
                                label="از سن"
                                onChange={(event) =>
                                  setSelectedAge1(event.target.value)
                                }
                              >
                                {selectAges.map((age) => (
                                  <MenuItem key={age} value={age}>
                                    {age}
                                  </MenuItem>
                                ))}
                              </Select>
                            </FormControl>
                          </Grid>
                          <Grid style={{ width: "80px" }}>
                            <FormControl fullWidth>
                              <InputLabel id="demo-simple-select-label">
                                تا سن
                              </InputLabel>
                              <Select
                                MenuProps={{
                                  PaperProps: {
                                    style: {
                                      maxHeight: 200, // Change the maximum height as needed
                                      width: 80, // Change the width as needed
                                    },
                                  },
                                }}
                                labelId="demo-simple-select-label"
                                id="demo-simple-select"
                                value={selectedAge2}
                                label="تا سن"
                                onChange={(event) =>
                                  setSelectedAge2(event.target.value)
                                }
                              >
                                {selectAges.map((age) => (
                                  <MenuItem key={age} value={age}>
                                    {age}
                                  </MenuItem>
                                ))}
                              </Select>
                            </FormControl>
                          </Grid>
                        </Grid>
                      )}
                    </Grid>

                    {filterType === "تاریخ" && (
                      <Grid container alignItems="center" gap={SPACING.SMALL}>
                        <Grid>
                          <Typography variant="caption">
                            فیلتر براساس تاریخ:
                          </Typography>
                        </Grid>
                        <Grid>
                          <DatePicker
                            label="از تاریخ"
                            id="date"
                            renderInput={(params) => (
                              <TextField
                                style={{ width: "160px" }}
                                {...params}
                              />
                            )}
                            value={selectedDate1}
                            onChange={(e) => {
                              setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                            }}
                          />
                        </Grid>
                        <Grid>
                          <DatePicker
                            label="تا تاریخ"
                            id="date"
                            renderInput={(params) => (
                              <TextField
                                style={{ width: "160px" }}
                                {...params}
                              />
                            )}
                            value={selectedDate2}
                            onChange={(e) => {
                              setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                            }}
                          />
                        </Grid>
                        <Grid>
                          <Button
                            variant="contained"
                            onClick={() => {
                              dispatch(
                                cityGetHatchings({
                                  selectedDate1,
                                  selectedDate2,
                                })
                              );
                            }}
                          >
                            جستجو
                          </Button>
                        </Grid>
                        <Tooltip title="خروجی اکسل">
                          <a
                            href={`${axios.defaults.baseURL}0/hatching_excel/?start=${selectedDate1}&end=${selectedDate2}`}
                            rel="noreferrer"
                          >
                            <Button color="success">
                              <RiFileExcel2Fill size={32} />
                            </Button>
                          </a>
                        </Tooltip>
                      </Grid>
                    )}
                  </Grid>
                }
                data={dataTable}
                columns={[
                  "ردیف",
                  "نام فارم",
                  "مرغدار",
                  "شهر/تعاونی",
                  "دامپزشک فارم",
                  "سالن",
                  "دوره جوجه ریزی",
                  "تاریخ ثبت جوجه ریزی",
                  "تاریخ جوجه ریزی",
                  "نژاد",
                  "سن",
                  "تعداد جوجه ریزی",
                  "تلفات دوره",
                  "کشتار شده",
                  "مانده در سالن",
                  "کشتار فعال",
                  "تعداد درخواست کشتار",
                  "آخرین تغییر",
                  "عملیات",
                ]}
              />
            </Grid>
          )} */}
          {view === "archive" && (
            <CityHatchingsArchive />
            // <Grid container width="100%" flex="1">
            // <AdvancedTable
            //   name={
            //     <Grid container alignItems="center" gap={SPACING.SMALL}>
            //       <Grid>
            //         <Typography>بایگانی جوجه ریزی</Typography>
            //       </Grid>
            //       <Grid>
            //         <DatePicker
            //           label="از تاریخ"
            //           id="date"
            //           renderInput={(params) => (
            //             <TextField style={{ width: "160px" }} {...params} />
            //           )}
            //           value={selectedDate1}
            //           onChange={(e) => {
            //             setSelectedDate1(moment(e).format("YYYY-MM-DD"));
            //           }}
            //         />
            //       </Grid>
            //       <Grid>
            //         <DatePicker
            //           label="تا تاریخ"
            //           id="date"
            //           renderInput={(params) => (
            //             <TextField style={{ width: "160px" }} {...params} />
            //           )}
            //           value={selectedDate2}
            //           onChange={(e) => {
            //             setSelectedDate2(moment(e).format("YYYY-MM-DD"));
            //           }}
            //         />
            //       </Grid>
            //       <Tooltip title="خروجی اکسل">
            //         <a
            //           href={`${axios.defaults.baseURL}0/hatching_excel/?start=${selectedDate1}&end=${selectedDate2}`}
            //           rel="noreferrer"
            //         >
            //           <Button color="success">
            //             <RiFileExcel2Fill size={32} />
            //           </Button>
            //         </a>
            //       </Tooltip>
            //     </Grid>
            //   }
            //   data={dataTableHatchingArchive}
            //   columns={[
            //     "ردیف",
            //     "نام فارم",
            //     "کدکاربری",
            //     "تلفن",
            //     "سالن",
            //     "دوره جوجه ریزی",
            //     "تاریخ ثبت جوجه ریزی",
            //     "تاریخ جوجه ریزی",
            //     "نژاد",
            //     "سن",
            //     "تعداد جوجه ریزی",
            //     "تلفات دوره",
            //     "کشتار شده",
            //     "مانده در سالن",
            //   ]}
            // />
            // </Grid>
          )}
        </Grid>
      </Grid>
    </Grid>
  );
};
