import {
  Button,
  Checkbox,
  FormControlLabel,
  Tab,
  Tabs,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import axios from "axios";
import moment from "moment/moment";
import { useContext, useEffect, useState } from "react";
import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri";
import { useDispatch, useSelector } from "react-redux";
import { Grid } from "../../../../components/grid/Grid";
import { AppContext } from "../../../../contexts/AppContext";
import { SPACING } from "../../../../data/spacing";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";
import { provinceGetAllocatedRequestsService } from "../../services/province-get-allocated-requests";
import { ProvinceAllocatedRequestsOperations } from "../province-allocated-requests-operations/ProvinceAllocatedRequestsOperations";
import { ProvinceGetDeletedAllocatedRequests } from "../province-get-deleted-allocated-requests/ProvinceGetDeletedAllocatedRequests";
import { provinceGetDashboardKillRequestService } from "../../services/get-dahsnoard-province-kill-request";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const ProvinceAllocatedRequests = () => {
  const dispatch = useDispatch();
  const [dataTable, setDataTable] = useState();
  const [hasDocumentState, setHasDocumentState] = useState(false);
  const [selectedTab, setSelectedTab] = useState(0);
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const userKey = useSelector((state) => state.userSlice.userProfile.key);

  const [textValue, setTextValue] = useState("");

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  const handleChangeDocumentState = (event) => {
    const checked = event.target.checked;
    setHasDocumentState(checked);

    dispatch(
      provinceGetAllocatedRequestsService({
        role_key: checkPathStartsWith("province")
          ? selectedSubUser?.key || ""
          : "",
        selectedDate1,
        selectedDate2,
        textValue,
        hasDocumentState: checked,
      })
    );

    fetchDashboard(checked);
  };

  const handleTabChange = (event, newValue) => {
    setSelectedTab(newValue);
  };

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

  const { provinceGetAllocatedRequests } = useSelector(
    (state) => state.provinceSlice
  );

  const [dashboardData, setDashboardData] = useState([]);

  const fetchDashboard = (checked = hasDocumentState) => {
    const params = {
      selectedDate1,
      selectedDate2,
      textValue,
      hasDocumentState: checked,
      role_key: checkPathStartsWith("province")
        ? selectedSubUser?.key || ""
        : "",
    };

    dispatch(provinceGetDashboardKillRequestService(params)).then((r) => {
      setDashboardData(r.payload.data);
    });
  };

  useEffect(() => {
    if (selectedTab === 0) {
      dispatch(
        provinceGetAllocatedRequestsService({
          role_key: checkPathStartsWith("province")
            ? selectedSubUser?.key || ""
            : "",
          selectedDate1,
          selectedDate2,
          textValue,
          hasDocumentState,
        })
      );
      fetchDashboard();
    }
  }, [selectedDate1, selectedDate2, selectedTab, selectedSubUser?.key]);

  const handleSubmit = () => {
    if (selectedTab === 0) {
      dispatch(
        provinceGetAllocatedRequestsService({
          role_key: checkPathStartsWith("province")
            ? selectedSubUser?.key || ""
            : "",
          selectedDate1,
          selectedDate2,
          textValue,
          hasDocumentState,
        })
      );
      fetchDashboard(hasDocumentState);
    }
  };

  useEffect(() => {
    const sortedRequests = provinceGetAllocatedRequests
      ?.slice()
      .sort((a, b) => b.allocatedRemainQuantity - a.allocatedRemainQuantity)
      .map((item, i) => {
        let state = "";
        if (item.allocatedState === "pending") {
          state = "در انتظار تایید";
        } else if (item.allocatedState === "accepted") {
          state = "تایید شده";
        } else if (item.allocatedState === "rejected") {
          state = "رد شده";
        }
        let sellType = "";
        if (item?.market) {
          sellType = "پنل معاملات";
        } else if (item?.directBuying) {
          sellType = "خرید مستقیم";
        } else if (item?.union) {
          sellType = "خرید خارج از استان";
        } else {
          sellType = "اتحادیه";
        }
        return [
          i + 1,
          item?.orderCode,
          sellType,
          item?.freeSaleInProvince === false ? "دولتی" : "آزاد",
          item?.freezing ? "انجماد" : item?.export ? "صادرات" : "عادی",
          item?.poultryUnitName,
          `${item?.poultryFullName} (${item?.poultryMobile})`,
          item?.poultryCity,
          formatJustDate(item?.sendDate),
          item?.poultryQuantity?.toLocaleString(),
          formatTime(item?.dateOfAllocate),
          item?.killHouseName,
          item?.killHouseCity,
          item?.allocatedQuantity?.toLocaleString(),
          item?.indexWeight?.toLocaleString(),
          item?.totalWeight?.toLocaleString(),
          item?.amount?.toLocaleString() + " ﷼",
          item?.killHousePrice?.toLocaleString() + " ﷼",
          state,
          item?.allocatedCarState ? "دارد" : "ندارد",
          item?.allocatedRemainQuantity?.toLocaleString(),
          item?.returnToProvince === false ? (
            <ProvinceAllocatedRequestsOperations
              item={item}
              key={i}
              fetchDashboard={fetchDashboard}
            />
          ) : (
            <Tooltip
              disableHoverListener={!item?.returner}
              key={i}
              title={
                <>
                  {item?.returner && (
                    <Grid
                      container
                      direction="column"
                      justifyContent="center"
                      xs={12}
                    >
                      <Typography variant="body2">
                        {item?.returner?.fullname || "-"} (
                        {item?.returner?.mobile || "-"})
                      </Typography>
                      <Typography variant="body2">
                        {item?.returner?.date
                          ? formatJustDate(item?.returner?.date)
                          : "-"}
                      </Typography>
                    </Grid>
                  )}
                </>
              }
            >
              <Typography
                variant="body2"
                sx={{
                  cursor: item?.returner ? "pointer" : "default",
                }}
              >
                تخصیص برگشت داده شده
              </Typography>
            </Tooltip>
          ),
        ];
      });
    setDataTable(sortedRequests);
  }, [provinceGetAllocatedRequests]);

  return (
    <Grid>
      <Grid
        container
        justifyContent="center"
        alignItems="center"
        mb={SPACING.MEDIUM}
        mt={SPACING.SMALL}
      >
        <Tabs
          scrollButtons="auto"
          variant="scrollable"
          allowScrollButtonsMobile
          value={selectedTab}
          onChange={handleTabChange}
        >
          <Tab label="تخصیص ها" />
          <Tab label="تخصیص های حذف شده" />
        </Tabs>
      </Grid>
      {selectedTab === 0 && (
        <Grid container alignItems="center" justifyContent="center">
          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <Grid style={{ width: 160 }}>
              <DatePicker
                label="از تاریخ"
                renderInput={(params) => <TextField {...params} />}
                value={selectedDate1}
                onChange={(e) => {
                  setSelectedDate1(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>
            <Grid style={{ width: 160 }}>
              <DatePicker
                label="تا تاریخ"
                renderInput={(params) => <TextField {...params} />}
                value={selectedDate2}
                onChange={(e) => {
                  setSelectedDate2(moment(e).format("YYYY-MM-DD"));
                }}
              />
            </Grid>

            <Grid container alignItems="center" gap={SPACING.SMALL}>
              <TextField
                size="small"
                autoComplete="off"
                label="جستجو"
                variant="outlined"
                style={{ width: 250 }}
                onChange={handleTextChange}
              />
              <Button
                type="submit"
                onClick={handleSubmit}
                endIcon={<RiSearchLine />}
              >
                جستجو
              </Button>
            </Grid>

            <Tooltip title="خروجی اکسل">
              <a
                href={`${
                  axios.defaults.baseURL
                }allocated_excel/?start=${selectedDate1}&end=${selectedDate2}&role=${getRoleFromUrl()}${
                  checkPathStartsWith("province")
                    ? `&role_key=${selectedSubUser?.key}`
                    : ""
                }&key=${userKey}&filter=search&value=${textValue}`}
                rel="noreferrer"
              >
                <Button color="success">
                  <RiFileExcel2Fill size={32} />
                </Button>
              </a>
            </Tooltip>

            <FormControlLabel
              control={
                <Checkbox
                  checked={hasDocumentState}
                  onChange={handleChangeDocumentState}
                  name="hasDocumentState"
                />
              }
              label="نمایش تخصیصات بدون بار"
            />
          </Grid>

          <Grid container mt={2} mb={4} isDashboard xs={12}>
            <ResponsiveTable
              noPagination
              isDashboard
              columns={[
                "تعداد تخصیصات",
                "حجم تخصیصات",
                "وزن تخصیصات",
                "تعداد تخصیصات تایید شده",
                "حجم تخصیصات تایید شده",
                "تعداد تخصیصات در انتظار تایید",
                "حجم تخصیصات در انتظار تایید",
                "تعداد تخصیصات رد شده",
                "حجم تخصیصات رد شده",
                "تعداد تخصیصات دارای ماشین",
                "حجم تخصیصات دارای ماشین",
                "وزن تخصیصات دارای ماشین",
                "تعداد بارها",
                "حجم بارها",
                "وزن بارها",
                "تعداد تخصیصات فاقد ماشین",
                "حجم تخصیصات فاقد ماشین",
                "وزن تخصیصات فاقد ماشین",
              ]}
              data={[
                [
                  dashboardData?.lenProvinceRequest?.toLocaleString(),
                  dashboardData?.quantity?.toLocaleString(),
                  dashboardData?.weight?.toLocaleString(),
                  dashboardData?.acceptedProvinceKillRequests?.toLocaleString(),
                  dashboardData?.acceptedProvinceKillRequestsQuantity?.toLocaleString(),
                  dashboardData?.pendingProvinceKillRequests?.toLocaleString(),
                  dashboardData?.pendingProvinceKillRequestsQuantity?.toLocaleString(),
                  dashboardData?.rejectedProvinceKillRequests?.toLocaleString(),
                  dashboardData?.rejectedProvinceKillRequestsQuantity?.toLocaleString(),
                  dashboardData?.lenHasCar?.toLocaleString(),
                  dashboardData?.hasCarQuantity?.toLocaleString(),
                  dashboardData?.hasCarWeight?.toLocaleString(),
                  dashboardData?.lenKillRequests?.toLocaleString(),
                  dashboardData?.realQuantity?.toLocaleString(),
                  dashboardData?.realWeight?.toLocaleString(),
                  dashboardData?.lenHasntCar?.toLocaleString(),
                  dashboardData?.hasntCarQuantity?.toLocaleString(),
                  dashboardData?.hasntCarWeight?.toLocaleString(),
                ],
              ]}
              title={"خلاصه اطلاعات"}
            />
          </Grid>

          <ResponsiveTable
            title="تخصیص های انجام شده"
            paginated
            noSearch
            columns={[
              "ردیف",
              "کدسفارش",
              "درخواست",
              "فروش",
              "کشتار",
              "نام فارم",
              "نام مرغدار",
              "شهر",
              "تاریخ کشتار",
              "تعداد کشتار",
              "تاریخ تخصیص",
              "خریدار",
              "شهر خریدار",
              "تعداد تخصیص",
              "میانگین وزنی",
              "وزن تقریبی",
              "قیمت مرغدار",
              "قیمت کشتارگاه",
              "وضعیت تایید خریدار",
              "وضعیت تخصیص ماشین",
              "مانده قابل تخصیص",
              "عملیات",
            ]}
            data={dataTable}
          />
        </Grid>
      )}
      {selectedTab === 1 && <ProvinceGetDeletedAllocatedRequests />}
    </Grid>
  );
};
