import {
  Accordion,
  AccordionDetails,
  AccordionSummary,
  Box,
  Button,
  Chip,
  Divider,
  Typography,
} from "@mui/material";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../components/grid/Grid";
import { SimpleTable } from "../components/simple-table/SimpleTable";
import { Timer } from "../components/timer/Timer";
import { SPACING } from "../data/spacing";
import { SlaughterHouseNewComplaint } from "../features/slaughter-house/components/slaughter-house-new-conmplaint/SlaughterHouseNewComplaint";
import { slaughterGetComplaints } from "../features/slaughter-house/services/slaughter-get-complaints";
import { slaughterGetRegisteredComplaints } from "../features/slaughter-house/services/slaughter-get-registered-complaints";
import {
  DRAWER,
  LOADING_END,
  LOADING_START,
} from "../lib/redux/slices/appSlice";
import { getRemainedSeconds } from "../utils/getRemainedSeconds";
import { getRoleFromUrl } from "../utils/getRoleFromUrl";
import { AdvancedTable } from "../components/advanced-table/AdvancedTable";
import { formatJustDate } from "../utils/formatTime";

const SlaughterComplaints = () => {
  const [dataTable, setDataTable] = useState();
  const [expanded, setExpanded] = useState(false);
  const handleChange = () => {
    setExpanded(!expanded);
  };
  const dispatch = useDispatch();
  const { slaughterHouseComplaints } = useSelector(
    (state) => state.slaughterSlice
  );

  const role = getRoleFromUrl();

  const { slaughterHouseRegisteredComplaints } = useSelector(
    (state) => state.slaughterSlice
  );

  useEffect(() => {
    dispatch(LOADING_START());
    dispatch(slaughterGetComplaints());
    dispatch(slaughterGetRegisteredComplaints()).then((r) => {
      dispatch(LOADING_END());
    });
  }, []);

  useEffect(() => {
    const d = slaughterHouseRegisteredComplaints?.map((item, i) => {
      return [
        item.title,
        item.description ? item.description : "بدون توضیحات",
        formatJustDate(item?.createDate),
        item.state === "pending"
          ? "در حال بررسی"
          : item.state === "accepted"
          ? "تایید شده"
          : "رد شده",
        item.percent,
        item.image?.length
          ? item.image?.map((item, i) => {
              return [
                <Grid
                  display="inline-flex"
                  key={`SlaughterPaymentFactorImage${i}`}
                >
                  <a href={item} alt="دانلود">
                    <img
                      src={item}
                      width="80"
                      height="80"
                      alt="دانلود"
                      style={{
                        marginRight: "10px",
                        borderRadius: "5px",
                      }}
                    />
                  </a>
                </Grid>,
              ];
            })
          : "بدون پیوست",
      ];
    });
    setDataTable(d);
  }, [slaughterHouseRegisteredComplaints]);

  const [filteredAvalableCompaints, setFilteredAvalableCompaints] = useState(
    []
  );

  const [filteredArchievedCompaints, setFilteredArchievedCompaints] = useState(
    []
  );
  useEffect(() => {
    setFilteredAvalableCompaints(
      slaughterHouseComplaints?.filter(
        (item) => getRemainedSeconds(item.protestTime) > 0
      )
    );

    setFilteredArchievedCompaints(
      slaughterHouseComplaints?.filter(
        (item) => getRemainedSeconds(item.protestTime) < 1
      )
    );
  }, [slaughterHouseComplaints]);

  return (
    <>
      <Box display={"flex"} justifyContent="center">
        <Grid
          container
          direction="column"
          justifyContent="center"
          xs={12}
          sm={12}
          md={10}
          lg={10}
        >
          <Grid container justifyContent="space-between" gap={SPACING.SMALL}>
            <Grid xs={12} mt={SPACING.MEDIUM}>
              <Accordion xs={12} expanded={expanded} onChange={handleChange}>
                <AccordionSummary
                  expandIcon={<ExpandMoreIcon />}
                  aria-controls="panel1a-content"
                  id="panel1a-header"
                >
                  <Typography>شکایات ثبت شده</Typography>
                </AccordionSummary>
                <AccordionDetails>
                  <Grid>
                    <AdvancedTable
                      columns={[
                        " موضوع",
                        " توضیحات",
                        " تاریخ ثبت",
                        " وضعیت",
                        "درصد تلفات",
                        "پیوست تصویر",
                      ]}
                      data={dataTable}
                    />
                  </Grid>
                </AccordionDetails>
              </Accordion>
              <Grid xs={12} mt={SPACING.MEDIUM}>
                {filteredAvalableCompaints?.length > 0 && (
                  <Divider>
                    <Chip label="بارهای تخصیص یافته" />
                  </Divider>
                )}
                {filteredAvalableCompaints?.map((item, i) => {
                  let remainedSeconds = getRemainedSeconds(item.protestTime);
                  const requestedSellTypeCash = item.cellType?.cash
                    ? "نقدی"
                    : null;
                  const requestedSellTypeCredit = item?.cellType?.credit
                    ? "زمان دار"
                    : null;
                  const requestedSellType = [
                    requestedSellTypeCash,
                    requestedSellTypeCredit,
                  ]
                    .filter((item) => item)
                    .join(" یا ");
                  return (
                    <>
                      <SimpleTable
                        key={i}
                        name="کد سفارش"
                        columns={[
                          "کد سفارش",
                          "نام مرغدار",
                          "تلفن",
                          "تاریخ درخواست کشتار",
                          "استان",
                          "شهرستان",
                          "تاریخ جوجه ریزی",
                          "تعداد",
                          "جمع تلفات",
                          "وزن تقریبی هر مرغ",
                          "سن مرغ",
                          "نژاد",
                          "نحوه فروش",
                        ]}
                        data={[
                          [
                            item.orderCode,
                            item.fullName,
                            item.mobile,
                            formatJustDate(item?.sendDate),
                            item.province,
                            item.city,
                            formatJustDate(item?.hatchingDate),
                            item.totalQuantity,
                            item.losses,
                            item.indexWeight,
                            item.age,
                            item.chickenBreed,
                            requestedSellType,
                          ],
                        ]}
                      />

                      <SimpleTable
                        key={i}
                        name="خودروهای دارای کد بار"
                        columns={[
                          "کشتارگاه",
                          "نام راننده",
                          "ماشین",
                          "نوع خرید",
                          "سند خودرو بدون بار",
                          "سند خودرو با بار",
                          "تعداد",
                          "وزن بار",
                          "میانگین وزن",
                          "مهلت ثبت شکایت",
                          "عملیات",
                        ]}
                        data={[
                          [
                            item.killHouse,
                            item.driverName,
                            item.car,
                            item.buyType === "cash" ? "نقد" : "نسیه",
                            <a
                              href={item.killHouseImageWithoutLoad}
                              alt="دانلود سند خودرو بدون بار"
                              key="provinceKillRequests"
                            >
                              <img
                                src={item.killHouseImageWithoutLoad}
                                width="50"
                                height="50"
                                alt="بدون بار"
                                className="images-file"
                              />
                            </a>,
                            <a
                              href={item.killHouseImageWithLoad}
                              alt="دانلود سند خودرو بدون بار"
                              key="provinceKillRequests"
                            >
                              <img
                                src={item.killHouseImageWithLoad}
                                width="50"
                                height="50"
                                alt="بدون بار"
                                className="images-file"
                              />
                            </a>,
                            item.killHouseRequestQuantity,
                            item.killHouseNetWeight,
                            Math.round(
                              (item.killHouseNetWeight /
                                item.killHouseRequestQuantity) *
                                100
                            ) / 100,
                            <Timer key={i} seconds={remainedSeconds} />,
                            <Button
                              disabled={remainedSeconds < 1}
                              key="test"
                              className="avicultureNewRequestBtn"
                              variant={"contained"}
                              onClick={() => {
                                dispatch(
                                  DRAWER({
                                    right: !(window.innerWidth <= 600),
                                    bottom: window.innerWidth <= 600,
                                    title: "ثبت شکایت جدید",
                                    content: (
                                      <SlaughterHouseNewComplaint
                                        barKey={item.killHouseAssignmentKey}
                                        role={role}
                                      />
                                    ),
                                  })
                                );
                              }}
                            >
                              ثبت شکایت
                            </Button>,
                            item.averageWeight,
                          ],
                        ]}
                      />
                    </>
                  );
                })}
              </Grid>
            </Grid>

            <Grid xs={12}>
              {filteredArchievedCompaints?.length > 0 && (
                <Divider>
                  <Chip label="بارهای بایگانی شده" />
                </Divider>
              )}
              {filteredArchievedCompaints?.map((item, i) => {
                const requestedSellTypeCash = item.cellType?.cash
                  ? "نقدی"
                  : null;
                const requestedSellTypeCredit = item?.cellType?.credit
                  ? "زمان دار"
                  : null;
                const requestedSellType = [
                  requestedSellTypeCash,
                  requestedSellTypeCredit,
                ]
                  .filter((item) => item)
                  .join(" یا ");
                return (
                  <>
                    <SimpleTable
                      key={i}
                      name="کد سفارش"
                      columns={[
                        "کد سفارش",
                        "نام مرغدار",
                        "تلفن",
                        "تاریخ درخواست کشتار",
                        "استان",
                        "شهرستان",
                        "تاریخ جوجه ریزی",
                        "تعداد",
                        "جمع تلفات",
                        "وزن تقریبی هر مرغ",
                        "سن مرغ",
                        "نژاد",
                        "نحوه فروش",
                      ]}
                      data={[
                        [
                          item.orderCode,
                          item.fullName,
                          item.mobile,
                          formatJustDate(item?.sendDate),
                          item.province,
                          item.city,
                          formatJustDate(item?.hatchingDate),
                          item.totalQuantity,
                          item.losses,
                          item.indexWeight,
                          item.age,
                          item.chickenBreed,
                          requestedSellType,
                        ],
                      ]}
                    />

                    <SimpleTable
                      key={i}
                      name="خودروهای دارای کد بار"
                      columns={[
                        "کشتارگاه",
                        "نام راننده",
                        "ماشین",
                        "نوع خرید",
                        "سند خودرو بدون بار",
                        "سند خودرو با بار",
                        "تعداد",
                        "وزن بار",
                        "میانگین وزن",
                      ]}
                      data={[
                        [
                          item.killHouse,
                          item.driverName,
                          item.car,
                          item.buyType === "cash" ? "نقد" : "نسیه",
                          <a
                            href={item.killHouseImageWithoutLoad}
                            alt="دانلود سند خودرو بدون بار"
                            key="provinceKillRequests"
                          >
                            <img
                              src={item.killHouseImageWithoutLoad}
                              width="50"
                              height="50"
                              alt="بدون بار"
                              className="images-file"
                            />
                          </a>,
                          <a
                            href={item.killHouseImageWithLoad}
                            alt="دانلود سند خودرو بدون بار"
                            key="provinceKillRequests"
                          >
                            <img
                              src={item.killHouseImageWithLoad}
                              width="50"
                              height="50"
                              alt="بدون بار"
                              className="images-file"
                            />
                          </a>,
                          item.killHouseRequestQuantity,
                          item.killHouseNetWeight,
                          Math.round(
                            (item.killHouseNetWeight /
                              item.killHouseRequestQuantity) *
                              100
                          ) / 100,
                        ],
                      ]}
                    />
                  </>
                );
              })}
            </Grid>
          </Grid>
        </Grid>
      </Box>
    </>
  );
};
export default SlaughterComplaints;
