import {
  Box,
  IconButton,
  TextField,
  ToggleButton,
  ToggleButtonGroup,
  Typography,
  Paper,
  Divider,
} from "@mui/material";
import { useContext, useEffect, useState } from "react";
import SettingsIcon from "@mui/icons-material/Settings";
import PlagiarismIcon from "@mui/icons-material/Plagiarism";
import { useNavigate } from "react-router-dom";
import { ROUTE_SLAUGHTER_HOUSE_VET_FILE } from "../../../../routes/routes";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";

import { useDispatch, useSelector } from "react-redux";
import { slaughterHouseVetNewRequests } from "../../services/slaughter-house-vet-new-requests";
import { DRAWER } from "../../../../lib/redux/slices/appSlice";
import EditIcon from "@mui/icons-material/Edit";
import SlaughterHouseVetCheckRequest from "../../../file/components/slaughter-house-vet-check-request/SlaughterHouseVetCheckRequest";
import { format } from "date-fns-jalali";
import moment from "moment/moment";
import { DatePicker } from "@mui/x-date-pickers";
import { AppContext } from "../../../../contexts/AppContext";
import { formatTime } from "../../../../utils/formatTime";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";

export const SlaughterHouseVetNewRequests = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [dataTable, setDataTable] = useState([]);
  const [dataTableMobile, setDataTableMobile] = useState([]);
  const [dataTableArchive, setDataTableArchive] = useState([]);
  const [dataTableArchiveMobile, setDataTableArchiveMobile] = useState([]);
  const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] =
    useContext(AppContext);

  useEffect(() => {
    const currentDate = moment(new Date()).format("YYYY-MM-DD");
    setSelectedDate1(currentDate);
    setSelectedDate2(currentDate);
  }, []);

  const { newRequests } = useSelector((state) => state.slaughterHouseVetSlice);

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

  useEffect(() => {
    const d = newRequests
      ?.filter((item) => item.vetState === "pending")
      .map((item, i) => {
        return [
          i + 1,
          item.barcod,
          item.clearanceCode ? item.clearanceCode : "ندارد",
          item.killHouseName,
          format(new Date(item?.sendDate), "yyyy/MM/dd"),
          formatTime(item?.createDate),
          `${item.poultryName} (${item.poultryMobile})`,
          item.killPlace,
          item.poultryCity,
          item.age,
          `${item.driverName} (${item.driverMobile})`,
          item.typeCar,
          item.pelak,

          item.chickenBreed,
          item?.quantity?.toLocaleString(),
          item.indexWeight,
          (item.indexWeight * item?.quantity).toLocaleString(),
          <IconButton
            key={i}
            color="primary"
            onClick={() => {
              dispatch(
                DRAWER({
                  title: "انجام عملیات تخلیه",

                  top: !(window.innerWidth <= 600),
                  bottom: window.innerWidth <= 600,
                  content: <SlaughterHouseVetCheckRequest item={item} />,
                })
              );
            }}
          >
            <EditIcon />
          </IconButton>,
        ];
      });

    setDataTable(d);

    const c = newRequests
      ?.filter((item) => item.vetState === "accepted")
      ?.map((item, i) => {
        return [
          i + 1,
          item.barcod,
          item.clearanceCode ? item.clearanceCode : "ندارد",
          item.killHouseName,
          format(new Date(item?.sendDate), "yyyy/MM/dd"),
          item.poultryName,
          item.poultryMobile,
          item.poultryCity,
          item?.age,
          item?.quantity?.toLocaleString() + " قطعه",
          item.driverName,
          item.typeCar,
          item.pelak,

          item.chickenBreed,
          item.indexWeight,
          <IconButton
            key={i}
            color="primary"
            className="avicultureActiveRequestsBtn"
            onClick={() =>
              navigate(ROUTE_SLAUGHTER_HOUSE_VET_FILE + item.poultryRequestId)
            }
          >
            <PlagiarismIcon />
          </IconButton>,
        ];
      });

    setDataTableArchive(c);

    const datam = newRequests
      ?.filter((item) => item.vetState === "pending")
      .map((item, i) => {
        return (
          <Grid item key={i} xs={6}>
            <Box
              key={i}
              component={Paper}
              style={{
                width: "100%",
                padding: "12px",
                borderRadius: "8px",
                boxShadow: "0 2px 5px rgba(0, 0, 0, 0.1)",
                marginBottom: "10px",
                display: "flex",
                flexDirection: "column",
              }}
            >
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                کد بار: {item.barcod}
              </Typography>
              <Divider />
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                کدرهگیری: {item.clearanceCode ? item.clearanceCode : "ندارد"}
              </Typography>
              <Divider />
              {}
              <Divider />
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                تاریخ کشتار: {format(new Date(item?.sendDate), "yyyy/MM/dd")}
              </Typography>
              <Divider />
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                مرغدار:
                <br />
                {`${item.poultryName} (${item.poultryMobile})`}
              </Typography>
              <Divider />
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                سن مرغ: {item.age}
              </Typography>
              <Divider />
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                تعداد: {item?.quantity?.toLocaleString()}
              </Typography>
              <Divider />
              <IconButton
                key={i}
                color="primary"
                style={{ marginTop: "8px" }}
                onClick={() => {
                  dispatch(
                    DRAWER({
                      title: "انجام عملیات تخصیص",
                      top: !(window.innerWidth <= 600),
                      bottom: window.innerWidth <= 600,
                      content: <SlaughterHouseVetCheckRequest item={item} />,
                    })
                  );
                }}
              >
                <SettingsIcon />
              </IconButton>
            </Box>
          </Grid>
        );
      });

    setDataTableMobile(datam);

    const archivem = newRequests
      ?.filter((item) => item.vetState === "accepted")
      .map((item, i) => {
        return (
          <Grid item key={i} xs={6}>
            <Box
              key={i}
              component={Paper}
              style={{
                width: "100%",
                padding: "12px",
                borderRadius: "8px",
                boxShadow: "0 2px 5px rgba(0, 0, 0, 0.1)",
                marginBottom: "10px",
                display: "flex",
                flexDirection: "column",
              }}
            >
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                کد بار: {item.barcod}
              </Typography>
              <Divider />
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                کدرهگیری: {item.clearanceCode ? item.clearanceCode : "ندارد"}
              </Typography>
              <Divider />
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                خریدار: {item.killHouseName}
              </Typography>
              <Divider />
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                تاریخ کشتار: {format(new Date(item?.sendDate), "yyyy/MM/dd")}
              </Typography>
              <Divider />
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                مرغدار:
                <br />
                {`${item.poultryName} (${item.poultryMobile})`}
              </Typography>
              <Divider />
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                سن مرغ: {item.age}
              </Typography>
              <Divider />
              <Typography style={{ fontSize: "14px", marginBottom: "8px" }}>
                تعداد: {item?.quantity?.toLocaleString()}
              </Typography>
              <Divider />
              <IconButton
                key={i}
                color="primary"
                className="avicultureActiveRequestsBtn"
                onClick={() =>
                  navigate(
                    ROUTE_SLAUGHTER_HOUSE_VET_FILE + item.poultryRequestId
                  )
                }
              >
                <PlagiarismIcon />
              </IconButton>
            </Box>
          </Grid>
        );
      });

    setDataTableArchiveMobile(archivem);
  }, [newRequests]);

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

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

  const isMobile = window.innerWidth <= 600;

  return (
    <Grid xs={12} container gap={SPACING.MEDIUM} direction="column">
      <Grid
        gap={SPACING.SMALL}
        justifyContent={{ xs: "center", lg: "space-between" }}
        alignSelf="center"
        alignItems="center"
        direction={{ xs: "column", lg: "row" }}
        xs={12}
      >
        <Grid container xs={12} alignItems={"end"} direction={"column"}>
          <Grid container>
            <ToggleButtonGroup
              color="primary"
              value={view}
              exclusive
              onChange={handleChange}
              aria-label="Platform"
            >
              <ToggleButton value="active">بارها</ToggleButton>
              <ToggleButton value="archive">بایگانی</ToggleButton>
            </ToggleButtonGroup>
          </Grid>

          {view === "active" && (
            <Grid
              width="100%"
              className="avicultureActiveRequestsView"
              container
            >
              {isMobile ? (
                <Grid
                  container
                  xs={12}
                  spacing={4}
                  justifyContent="space-between"
                >
                  <Grid
                    container
                    alignItems="center"
                    gap={SPACING.SMALL}
                    justifyContent="center"
                    marginBottom={2}
                  >
                    <Grid xs={12}>
                      <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>
                  </Grid>
                  {dataTableMobile}
                </Grid>
              ) : (
                <ResponsiveTable
                  title={
                    <Grid
                      container
                      alignItems="center"
                      gap={SPACING.SMALL}
                      mb={2}
                    >
                      <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>
                    </Grid>
                  }
                  columns={[
                    "ردیف",
                    "کد بار",
                    "کدرهگیری سامانه قرنطینه",
                    "خریدار",
                    "تاریخ کشتار",
                    "تاریخ ثبت خودرو",
                    "مرغدار",
                    "محل کشتار",
                    "شهر",
                    "سن مرغ",
                    "راننده",
                    "ماشین",
                    "پلاک",

                    "نژاد",
                    "تعداد (قطعه)",
                    "میانگین وزن",
                    "وزن تقریبی بار (کیلوگرم)",
                    "عملیات",
                  ]}
                  data={dataTable}
                  paginated
                />
              )}
            </Grid>
          )}
          {view === "archive" && (
            <Grid xs={12} className="avicultureActiveRequestsView">
              {isMobile ? (
                <Grid
                  container
                  xs={12}
                  spacing={4}
                  justifyContent="space-between"
                >
                  <Grid
                    container
                    alignItems="center"
                    gap={SPACING.SMALL}
                    justifyContent="center"
                    marginBottom={2}
                  >
                    <Grid xs={12}>
                      <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>
                  </Grid>
                  {dataTableArchiveMobile}
                </Grid>
              ) : (
                <ResponsiveTable
                  title={
                    <Grid
                      container
                      alignItems="center"
                      gap={SPACING.SMALL}
                      mb={2}
                    >
                      <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>
                    </Grid>
                  }
                  columns={[
                    "ردیف",
                    "کد بار",
                    "کدرهگیری سامانه قرنطینه",
                    "خریدار",
                    "تاریخ درخواست",
                    "مرغدار",
                    "تلفن مرغدار",
                    "شهر",
                    "سن مرغ",
                    "تعداد",
                    "راننده",
                    "ماشین",
                    "پلاک",

                    "نژاد",
                    "میانگین وزن",
                    "مشاهده",
                  ]}
                  data={dataTableArchive}
                  paginated
                />
              )}
            </Grid>
          )}
        </Grid>
      </Grid>
    </Grid>
  );
};
