import {
  Collapse,
  IconButton,
  Paper,
  Tooltip,
  Typography,
} from "@mui/material";
import { useEffect, useState, useRef, useContext } from "react";
import { Grid } from "../../../../components/grid/Grid";
import { ProvinceCaseOverview } from "../province-case-overview/ProvinceCaseOverview";
import { ProvinceCaseSteps } from "../province-case-steps/ProvinceCaseSteps";
import { ProvinceCaseStepPaymentInformation } from "../province-case-step-payment-information/ProvinceCaseStepPaymentInformation";
import { BsFillFileEarmarkPdfFill } from "react-icons/bs";
import { useReactToPrint } from "react-to-print";
import { AppContext } from "../../../../contexts/AppContext";
import ProvinceGetCaseFile from "../province-get-case-file/ProvinceGetCaseFile";
import { formatJustDate } from "../../../../utils/formatTime";
import {
  TableCityLevel,
  TableProvinceLevel,
  TableSVetAcceptDischarge,
  TableSalughterAllocationLevel,
  TableSlaughterAddCar,
  TableSlaughterInputBarData,
} from "./Pages";

export const ProvinceCasesItem = ({ caseData, caseIndex, pageIndex, data }) => {
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [clickedStep, setClickedStep] = useState(null);

  const [statusColor, setStatusColor] = useState("black");

  const [, , selectedDate1] = useContext(AppContext);

  const [currentStep, setCurrentStep] = useState("تایید شهرستان");

  useEffect(() => {
    let step = "تایید شهرستان";

    if (
      caseData?.cityState?.state === "reject" ||
      caseData?.provinceState?.state === "reject"
    ) {
      step = "درخواست رد شد";
      setStatusColor("red");
    } else {
      if (caseData?.cityState?.date) {
        step = "تایید شهرستان";
      }
      if (caseData?.provinceState?.date) {
        step = "تایید استان";
      }
      if (
        caseData?.provinceKillRequests?.provinceKillRequestSerializer?.length >
        0
      ) {
        step = "تخصیص به خریدار";
      }
      if (
        caseData?.killHouseRequests?.killHouseRequestsSerializer?.length > 0
      ) {
        step = "ایجاد بار";
      }
      if (
        caseData?.killHouseRequests?.killHouseRequestVetCheckSerializer
          ?.length > 0
      ) {
        step = "تخلیه بار";
      }
      if (
        caseData?.killHouseRequests?.killHouseRequestAssignmentSerializer
          ?.length > 0
      ) {
        step = "اطلاعات بار";
      }
    }

    setCurrentStep(step);
  }, [caseData]);

  const componentRef = useRef();
  const printPDF = useReactToPrint({
    content: () => componentRef.current,
    documentTitle: `گزارش پرونده `,
  });

  const setPdfOptions = () => {
    if (caseData) {
      printPDF();
    }
  };

  const handleToggleCollapse = () => {
    setIsCollapsed(!isCollapsed);
  };

  const stepClickedHandler = (step) => {
    setClickedStep(step);
  };

  let clickedStepComponent;

  switch (clickedStep) {
    case 1:
      clickedStepComponent = <TableCityLevel item={caseData} />;
      break;
    case 2:
      clickedStepComponent = <TableProvinceLevel item={caseData} />;
      break;
    case 3:
      clickedStepComponent = <TableSalughterAllocationLevel item={caseData} />;
      break;
    case 4:
      clickedStepComponent = <TableSlaughterAddCar item={caseData} />;
      break;
    case 5:
      clickedStepComponent = <TableSVetAcceptDischarge item={caseData} />;
      break;
    case 6:
      clickedStepComponent = <TableSlaughterInputBarData item={caseData} />;
      break;
    case 7:
      clickedStepComponent = <ProvinceCaseStepPaymentInformation />;
      break;
    default:
      break;
  }

  return (
    <Paper>
      <Grid container direction="row" mb={2}>
        <div
          style={{
            width: "3%",
            background: caseData.out ? "rgb(255 123 123)" : "rgb(172 235 230)",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            flexDirection: "column",
          }}
        >
          <Typography color={caseData?.out ? "white" : "grey"}>
            {pageIndex + caseIndex}.
          </Typography>
          <div
            style={{
              background: caseData.out
                ? "rgb(255 123 123)"
                : "rgb(172 235 230)",
              writingMode: "vertical-rl",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              width: "100%",
            }}
          >
            <Typography
              style={{
                background: "#2196f3",
                borderRadius: "10px",
                padding: "2px",
                color: "white",
                fontSize: "10px",
              }}
            >
              {caseData.out ? "خارج استان" : "داخل استان"}
            </Typography>
          </div>
          <div style={{ height: "10px" }}></div>
        </div>
        <div style={{ width: "97%" }}>
          <Grid
            style={{
              backgroundColor:
                caseIndex % 2 === 0 ? "white" : "rgb(247, 249, 250)",
              padding: "10px",
              cursor: "pointer",
              width: "100%",
            }}
          >
            <div style={{ visibility: "hidden", position: "absolute" }}>
              <ProvinceGetCaseFile
                ref={componentRef}
                item={caseData}
                inDate={selectedDate1}
                reportType={"slaughter"}
              />
            </div>
            <Grid
              container
              onClick={handleToggleCollapse}
              justifyContent="space-between"
              alignItems="center"
              height="100px"
            >
              <Grid xs={2}>
                <Typography variant="body2">
                  شماره سفارش: {caseData?.orderCode}
                </Typography>
              </Grid>

              <Grid xs={2}>
                <Typography variant="body2" color={statusColor}>
                  نوع کشتار: {caseData?.freezing ? "انجماد" : "عادی"}
                </Typography>
              </Grid>

              <Grid xs={2}>
                <Typography variant="body2">
                  تاریخ کشتار: {formatJustDate(caseData?.sendDate)}
                </Typography>
              </Grid>

              <Grid xs={2}>
                <Typography variant="body2">
                  مرغدار: {caseData?.poultry?.unitName}
                </Typography>
              </Grid>

              <Grid xs={2}>
                <Typography variant="body2" color={statusColor}>
                  وضعیت: {currentStep}
                </Typography>
              </Grid>

              <Grid xs={1}>
                <Tooltip title="خروجی PDF">
                  <IconButton
                    aria-label="delete"
                    color="success"
                    onClick={setPdfOptions}
                  >
                    <BsFillFileEarmarkPdfFill size={25} />
                  </IconButton>
                </Tooltip>
              </Grid>
            </Grid>
          </Grid>
          <Collapse in={isCollapsed}>
            <Grid style={{ padding: "20px" }}>
              <ProvinceCaseOverview item={caseData} />
              <ProvinceCaseSteps
                stepClickedHandler={stepClickedHandler}
                item={caseData}
              />
              {clickedStepComponent}
            </Grid>
          </Collapse>
        </div>
      </Grid>
    </Paper>
  );
};
