import {
  Checkbox,
  FormControl,
  FormControlLabel,
  IconButton,
  InputLabel,
  MenuItem,
  Radio,
  Select,
  Tab,
  Tabs,
  Tooltip,
  Typography,
} from "@mui/material";
import { useEffect, useState } from "react";
import { useDispatch } from "react-redux";

import { useNavigate } from "react-router-dom";
import LiveHelpIcon from "@mui/icons-material/LiveHelp";
import { Grid } from "../../../../components/grid/Grid";
import {
  ROUTE_ADMINX_ROUTE_POLICY_COUNCIL_FREE_SALE,
  ROUTE_PROVINCE_ROUTE_POLICY_COUNCIL_FREE_SALE,
  ROUTE_PROVINCE_ROUTE_POLICY_COUNCIL_POULTRY_CHOOSE_SLAUGHTER,
  ROUTE_SUPER_ADMIN_ROUTE_POLICY_COUNCIL_FREE_SALE,
} from "../../../../routes/routes";
import { provinceGetPolicyPoultryChooseKillHouseService } from "../../services/province-get-policy-poultry-choose-kill-house";
import { provincePolicyFreeSaleService } from "../../services/province-policy-free-sale";
import { provincePolicyGetFreeSaleService } from "../../services/province-policy-get-free-sale";
import { provincePolicyPoultryChooseKillHouseService } from "../../services/province-policy-poultry-choose-kill-house";
import TuneIcon from "@mui/icons-material/Tune";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { hourLimitKillRequestService } from "../../../city/services/hour-limit-kill-request";
import { provincePolicyAutoAcceptSlaughterService } from "../../services/province-policy-auto-accept-slaughter";
import { provincePolicyGetAutoAcceptSlaughterService } from "../../services/province-policy-get-auto-accept-slaughter";
import { provincePolicyAutoAllocateCarService } from "../../services/province-policy-auto-allocate-car";
import { provincePolicyGetAutoAllocateCarService } from "../../services/province-policy-get-auto-allocate-car";

import { ProvinceApplyDefaultLosses } from "../province-apply-default-losses/ProvinceApplyDefaultLosses";
import { ProvinceSlaughterDirectBuyPermission } from "../province-slaughter-direct-buy-permission/ProvinceSlaughterDirectBuyPermission";
import { ProvincePolicyKillhouseHourLimit } from "../province-policy-killhouse-hour-limit/ProvincePolicyKillhouseHourLimit";
import { hourLimitGetKillRequestService } from "../../../city/services/hour-limit-get-kill-request";
import { ProvincePolicyProvinceFee } from "../province-policy-province-fee/ProvincePolicyProvinceFee";
import { provinceGetEvacuationPermit } from "../../services/province-get-evacuation-permit";

import { provinceEditEvacuationPermit } from "../../services/province-edit-evacuation-permit";
import { provinceGetSellForFreezingStatus } from "../../services/province-get-sell-for-freezing-status";
import { provinceSetSellForFreezing } from "../../services/province-set-sell-for-freezing-access";
import ProvincePolicyLimitAccess from "../province-policy-limit-access/ProvincePolicyLimitAccess";
import { ProvincePolicyApprovedPrice } from "../province-policy-approved-price/ProvincePolicyApprovedPrice";
import { ProvincePolicySlaughterAge } from "../province-policy-slaughter-age/ProvincePolicySlaughterAge";
import { ProvincePolicyTimeRange } from "../province-policy-time-range/ProvincePolicyTimeRange";
import ProvincePolicyWageFractions from "../province-policy-wage-fractions/ProvincePolicyWageFractions";
import { ProvincePolicyCouncilAllowFreeSale } from "../province-policy-council-allow-free-sale/ProvincePolicyCouncilAllowFreeSale";
import { ProvincePolicyCouncilAllowExport } from "../province-policy-council-allow-export/ProvincePolicyCouncilAllowExport";
import { ProvincePolicyCouncilAllowAggegateBarInfo } from "../province-policy-council-allow-aggregate-bar-info/ProvincePolicyCouncilAllowAggegateBarInfo";
import { ProvincePolicyCouncilMaximumBarQuantity } from "../province-policy-council-maximum-bar-quantity/ProvincePolicyCouncilMaximumBarQuantity";
import { ProvincePolicyCouncilSlaughterSubmitBuyingPrice } from "../province-policy-council-slaughter-submit-buying-price/ProvincePolicyCouncilSlaughterSubmitBuyingPrice";
import { ProvincePolicyAutomaticAcceptDirectBuying } from "../province-policy-automatic-accept-direct-buying/ProvincePolicyAutomaticAcceptDirectBuying";
import { ProvincePolicyCouncilValidatePoultryWithSms } from "../province-policy-council-validate-poultry-with-sms/ProvincePolicyCouncilValidatePoultryWithSms";
import { ProvincePolicyDropLimit } from "../province-policy-slaughter-drop-limit/ProvincePolicyDropLimit";
import { ProvincePolicyUploadSlaughterInProvinceImage } from "../province-policy-upload-image_slaughter_in_province/ProvincePolicyUploadSlaughterInProvinceImage";
import { ProvincePolicyUploadImageSlaughterOutProvince } from "../province_policy_upload_image_slaughter_out_province/ProvincePolicyUploadImageSlaughterOutProvince";
import { ProvincePolicyUploadStewardInProvinceImage } from "../province-policy-steward-in-province-Upload-image/ProvincePolicyUploadStewardInProvinceImage";
import { ProvincePolicyUploadImageStewardOutProvince } from "../province-policy-steward-out-province-upload-image/ProvincePolicyUploadImageStewardOutProvince";

import { ProvincePolicyDirectBuying } from "../province-policy-direct-buying/ProvincePolicyDirectBuying";
import { ProvincePolicyTradeTimeRange } from "../province-policy-trade-time-range/ProvincePolicyTradeTimeRange";
import { ProvinceMandatorySuperVisorAuthenticationCode } from "../province-mandatory-supervisor-authentication-code/ProvinceMandatorySuperVisorAuthenticationCode";
import { ProvinceMandatorySlaughterhouseVerificationCode } from "../province-mandatory-slaughterhouse-verification-code/ProvinceMandatorySlaughterhouseVerificationCode";
import { ProvincePolicyDirectPurchaseBarLimitation } from "../province-policy-direct-purchase-bar-limitation/ProvincePolicyDirectPurchaseBarLimitation";
import { ManageEvacuations } from "../manage-evacuations/ManageEvacuations";
import { ProvincePolicyMarketDailyLimitation } from "../province-policy-market-daily-limitation/ProvincePolicyMarketDailyLimitation";
import { ProvinceHatchingArchivePercent } from "../province-hatching-archive-percent/ProvinceHatchingArchivePercent";

export const ProvincePolicyCouncil = () => {
  const [isFirstLoad, setIsFirstLoad] = useState(true);
  const [value, setValue] = useState("0");
  const [freeSale, setFreeSale] = useState(false);

  const [poultryChooseSlaughter, setPoultryChooseSlaughter] = useState(false);
  const [autoAcceptSlaughter, setAutoAcceptSlaughter] = useState(false);
  const [autoCarAllocateSlaughter, setAutoCarAllocateSlaughter] =
    useState(false);

  const dispatch = useDispatch();
  const navigate = useNavigate();
  const hours = Array.from({ length: 8 }, (_, i) => i + 8);
  const [isChecked, setIsChecked] = useState(false);
  const [selectedHour, setSelectedHour] = useState("");
  const [evacuationBeforeQuarantineCode, setEvacuationBeforeQuarantineCode] =
    useState("optional");
  const [sellForFreezing, setSellForFreezing] = useState(false);

  const [hovered, setHovered] = useState(false);

  const [mandatory, setMandatory] = useState(false);

  const handleChange = (event) => {
    if (event.target.name === "item1") {
      setFreeSale(event.target.checked);
      dispatch(
        provincePolicyFreeSaleService({
          allow: event.target.checked,
        })
      );
    }

    if (event.target.name === "item6") {
      setPoultryChooseSlaughter(event.target.checked);
      dispatch(
        provincePolicyPoultryChooseKillHouseService({
          allow: event.target.checked,
          mandatory,
        })
      );
    }

    if (event.target.name === "autoAcceptSlaughter") {
      setAutoAcceptSlaughter(event.target.checked);
      dispatch(
        provincePolicyAutoAcceptSlaughterService({
          allow: event.target.checked,
        })
      );
    }

    if (event.target.name === "autoCarAllocateSlaughter") {
      setAutoCarAllocateSlaughter(event.target.checked);
      dispatch(
        provincePolicyAutoAllocateCarService({
          allow: event.target.checked,
        })
      );
    }
  };

  useEffect(() => {
    dispatch(provincePolicyGetFreeSaleService()).then((r) => {
      setFreeSale(r.payload.data);
    });

    dispatch(provinceGetPolicyPoultryChooseKillHouseService()).then((r) => {
      setPoultryChooseSlaughter(r.payload.data.allowState);
      setMandatory(r.payload.data.mandatory);
    });

    dispatch(provincePolicyGetAutoAcceptSlaughterService()).then((r) => {
      setAutoAcceptSlaughter(r.payload.data);
    });

    dispatch(provincePolicyGetAutoAllocateCarService()).then((r) => {
      setAutoCarAllocateSlaughter(r.payload.data);
    });

    dispatch(provinceGetEvacuationPermit()).then((r) => {
      setEvacuationBeforeQuarantineCode(r.payload.data.type);
    });

    dispatch(provinceGetSellForFreezingStatus()).then((r) => {
      setSellForFreezing(r.payload.data.permission);
    });
  }, []);

  useEffect(() => {
    setIsFirstLoad(false);
    if (!isFirstLoad) {
      dispatch(
        provincePolicyPoultryChooseKillHouseService({
          allow: poultryChooseSlaughter,
          mandatory,
        })
      );
    }
  }, [mandatory]);

  useEffect(() => {
    if (isChecked && selectedHour) {
      dispatch(
        hourLimitKillRequestService({ hour: selectedHour, active: isChecked })
      );
    }
    if (!isChecked && selectedHour) {
      setSelectedHour(null);
      dispatch(hourLimitKillRequestService({ hour: 0, active: isChecked }));
    }
  }, [selectedHour, isChecked]);

  useEffect(() => {
    dispatch(hourLimitGetKillRequestService()).then((r) => {
      setIsChecked(r.payload.data.active);
      setSelectedHour(r.payload.data.hour);
    });
  }, []);

  const handleChangeEvacuationPermit = (e) => {
    dispatch(provinceEditEvacuationPermit({ type: e })).then(() => {
      dispatch(provinceGetEvacuationPermit()).then((r) => {
        setEvacuationBeforeQuarantineCode(r.payload.data.type);
      });
    });
  };

  const handleChangeSellForFreezing = (e) => {
    dispatch(provinceSetSellForFreezing({ permission: e })).then(() => {
      dispatch(provinceGetSellForFreezingStatus()).then((r) => {
        setSellForFreezing(r.payload.data.permission);
      });
    });
  };
  const handleChangeTab = (event, newValue) => {
    setValue(newValue);
  };

  return (
    <Grid
      container
      xs={12}
      justifyContent="center"
      alignItems="center"
      mb={4}
      sx={{ background: "#F9F9F9", borderRadius: "15px" }}
    >
      <Grid
        container
        xs={12}
        justifyContent="center"
        alignItems="center"
        mb={4}
        mt={2}
      >
        <Typography xs={12}>مدیریت فرآیند</Typography>
      </Grid>

      <Tabs
        value={value}
        onChange={handleChangeTab}
        textColor="secondary"
        indicatorColor="secondary"
        aria-label="secondary tabs example"
      >
        <Tab value="0" label="صدور مجوز" />
        <Tab value="1" label="محدودیت و اولویت" />
        {/* <Tab value="2" label="سهم بندی" /> */}
        <Tab value="3" label="قیمت مصوب" />
        <Tab value="4" label="مدیریت تلفات" />
      </Tabs>

      {value === "0" && (
        <Grid
          container
          xs={12}
          justifyContent="center"
          alignItems="center"
          mt={2}
        >
          <Grid
            container
            xs={12}
            gap={2}
            alignItems="start"
            className="manage-process"
            direction="column"
          >
            <Grid
              xs={12}
              container
              justifyContent="center"
              alignItems="center"
              gap={2}
            >
              <Grid
                isPolicy
                container
                justifyContent="center"
                isLocked
                sx={{
                  height: "60px",
                  width: {
                    xs: "100%",
                    sm: "48%",
                    lg: "19%",
                  },
                }}
                xs={12}
              >
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={true}
                      onChange={handleChange}
                      name="item4"
                    />
                  }
                  label="مدیر اجرایی (اتحادیه)"
                />
              </Grid>
              <Grid
                isPolicy
                container
                justifyContent="center"
                sx={{ height: "60px", width: "340px" }}
              >
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={freeSale}
                      onChange={handleChange}
                      name="item1"
                    />
                  }
                  label="مجوز فروش به خارج استان (زنده)"
                />
                <Tooltip title="مدیریت">
                  <IconButton
                    disabled={!freeSale}
                    color="success"
                    onClick={() => {
                      navigate(
                        getRoleFromUrl() === "ProvinceOperator"
                          ? ROUTE_PROVINCE_ROUTE_POLICY_COUNCIL_FREE_SALE
                          : getRoleFromUrl() === "SuperAdmin"
                          ? ROUTE_SUPER_ADMIN_ROUTE_POLICY_COUNCIL_FREE_SALE
                          : ROUTE_ADMINX_ROUTE_POLICY_COUNCIL_FREE_SALE
                      );
                    }}
                  >
                    <TuneIcon />
                  </IconButton>
                </Tooltip>
              </Grid>
            </Grid>
            <Grid
              xs={12}
              container
              justifyContent="center"
              alignItems="start"
              gap={2}
              px={2}
            >
              <ProvincePolicyDirectBuying />

              <Grid
                container
                alignItems="center"
                isPolicy
                gap={2}
                sx={{
                  width: {
                    xs: "100%",
                    sm: "48%",
                    lg: "19%",
                  },
                }}
              >
                <Typography variant="body1">تخلیه با کد قرنطینه</Typography>
                <Grid xs={12} container justifyContent="space-between">
                  <FormControlLabel
                    control={
                      <Radio
                        name="item6"
                        checked={evacuationBeforeQuarantineCode !== "optional"}
                        onClick={() => {
                          handleChangeEvacuationPermit("force");
                        }}
                      />
                    }
                    label="اجباری"
                  />
                  <FormControlLabel
                    control={
                      <Radio
                        checked={evacuationBeforeQuarantineCode === "optional"}
                        onClick={() => {
                          handleChangeEvacuationPermit("optional");
                        }}
                        name="item6"
                      />
                    }
                    label="اختیاری"
                  />
                </Grid>
              </Grid>
              <Grid
                container
                alignItems="center"
                isPolicy
                gap={2}
                sx={{
                  width: {
                    xs: "100%",
                    sm: "48%",
                    lg: "19%",
                  },
                }}
              >
                <Typography variant="body1">
                  مجوز فروش مرغ برای انجماد
                </Typography>
                <Grid xs={12} container justifyContent="space-between">
                  <FormControlLabel
                    control={
                      <Radio
                        name="item6"
                        checked={sellForFreezing}
                        onClick={() => {
                          handleChangeSellForFreezing(true);
                        }}
                      />
                    }
                    label="فعال"
                  />
                  <FormControlLabel
                    control={
                      <Radio
                        checked={!sellForFreezing}
                        onClick={() => {
                          handleChangeSellForFreezing(false);
                        }}
                        name="item6"
                      />
                    }
                    label="غیر فعال"
                  />
                </Grid>
              </Grid>
              <ProvincePolicyCouncilAllowAggegateBarInfo />
              <ProvincePolicyCouncilAllowFreeSale />
              <ProvincePolicyCouncilAllowExport />
              <ProvincePolicyCouncilSlaughterSubmitBuyingPrice />
              <ProvincePolicyCouncilValidatePoultryWithSms />
              <ProvincePolicyCouncilMaximumBarQuantity />
              <ProvincePolicySlaughterAge />
              <ProvincePolicyAutomaticAcceptDirectBuying />
              <ProvincePolicyUploadSlaughterInProvinceImage />
              <ProvincePolicyUploadImageSlaughterOutProvince />
              <ProvincePolicyUploadStewardInProvinceImage />
              <ProvincePolicyUploadImageStewardOutProvince />
              <ProvincePolicyTradeTimeRange />
              <ProvinceMandatorySuperVisorAuthenticationCode />
              <ProvinceMandatorySlaughterhouseVerificationCode />
              <ProvincePolicyDirectPurchaseBarLimitation />
              <ProvincePolicyMarketDailyLimitation />
              <ProvinceHatchingArchivePercent />
              <ProvincePolicyDropLimit />
            </Grid>

            <ProvincePolicyTimeRange />
          </Grid>
        </Grid>
      )}

      {value === "1" && (
        <Grid
          container
          xs={12}
          justifyContent="center"
          alignItems="start"
          direction="column"
          mt={2}
        >
          <ProvincePolicyLimitAccess />
          <Grid container>
            <FormControlLabel
              control={
                <Checkbox
                  checked={poultryChooseSlaughter}
                  onChange={handleChange}
                  name="item6"
                />
              }
              label="اولویت بندی کشتارگاه توسط مرغدار"
            />
            <Tooltip title="مدیریت" aria-label="choose-slaughter">
              <IconButton
                disabled={!poultryChooseSlaughter}
                color="success"
                onClick={() => {
                  navigate(
                    ROUTE_PROVINCE_ROUTE_POLICY_COUNCIL_POULTRY_CHOOSE_SLAUGHTER
                  );
                }}
              >
                <TuneIcon />
              </IconButton>
            </Tooltip>
            {poultryChooseSlaughter && (
              <>
                <FormControlLabel
                  control={
                    <Radio
                      value={true}
                      name="item6"
                      checked={mandatory === true}
                      onChange={() => setMandatory(true)}
                    />
                  }
                  label="اجباری"
                />
                <FormControlLabel
                  control={
                    <Radio
                      checked={mandatory === false}
                      onChange={() => setMandatory(false)}
                      value={false}
                      name="item6"
                    />
                  }
                  label="اختیاری"
                />
              </>
            )}
          </Grid>
          <FormControlLabel
            control={
              <Checkbox checked={""} onChange={handleChange} name="item2" />
            }
            label="فروش خارج از شبکه"
          />
          <FormControlLabel
            control={
              <Checkbox checked={""} onChange={handleChange} name="item3" />
            }
            label="فعال سازی پنل بورس"
          />
          <Grid container>
            <FormControlLabel
              control={
                <Checkbox checked={""} onChange={handleChange} name="item5" />
              }
              label="تسویه حساب مالی"
            />
            <Tooltip
              title="در صورت فعال بودن این فیلتر امکان تخصیص حجم بار به کشتارگاه یا کشتارکن که بدهی از قبل دارد وجود ندارد."
              open={hovered}
              placement="bottom"
            >
              <IconButton
                aria-label="help"
                onMouseOver={() => setHovered(true)}
                onMouseLeave={() => setHovered(false)}
              >
                <LiveHelpIcon />
              </IconButton>
            </Tooltip>
          </Grid>

          {(getRoleFromUrl() === "ProvinceOperator" ||
            getRoleFromUrl() === "SuperAdmin") && (
            <ProvincePolicyKillhouseHourLimit />
          )}
          {(getRoleFromUrl() === "ProvinceOperator" ||
            getRoleFromUrl() === "SuperAdmin") && (
            <Grid container gap={2}>
              <FormControlLabel
                control={
                  <Checkbox
                    checked={isChecked}
                    onChange={() => setIsChecked(!isChecked)}
                  />
                }
                label="محدودیت زمان درخواست کشتار مرغدار"
              />
              {isChecked && (
                <FormControl style={{ width: 200 }}>
                  <InputLabel id="hour-label">ساعت پایان درخواست</InputLabel>
                  <Select
                    labelId="hour-label"
                    label="ساعت پایان درخواست"
                    id="hour-select"
                    value={selectedHour}
                    onChange={(event) => setSelectedHour(event.target.value)}
                  >
                    {hours.map((hour) => (
                      <MenuItem key={hour} value={hour}>
                        {hour}:00
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              )}
            </Grid>
          )}
          <FormControlLabel
            control={
              <Checkbox
                name="autoAcceptSlaughter"
                checked={autoAcceptSlaughter}
                onChange={handleChange}
              />
            }
            label="تایید خودکار حجم تخصیصی به کشتارگاه"
          />
          <FormControlLabel
            control={
              <Checkbox
                checked={autoCarAllocateSlaughter}
                onChange={handleChange}
                name="autoCarAllocateSlaughter"
                disabled="true"
              />
            }
            label="ایجاد خودروی حمل بار برای کشتارگاه"
          />
          <FormControlLabel
            control={
              <Checkbox checked={""} onChange={handleChange} name="item2" />
            }
            label="عدم امکان وارد کردن اطلاعات بار در صورت تایید نکردن تخلیه دامپزشک کشتارگاه"
          />
          <ProvinceApplyDefaultLosses />
          <ProvinceSlaughterDirectBuyPermission />
          {/* <ProvincePolicyKillhouseGuilds /> */}
          <ProvincePolicyProvinceFee />
        </Grid>
      )}

      {value === "2" && (
        <Grid container xs={12} justifyContent="center" alignItems="center">
          <ProvincePolicyWageFractions />
        </Grid>
      )}

      {value === "3" && (
        <Grid
          container
          xs={12}
          justifyContent="center"
          alignItems="center"
          gap={2}
        >
          <ProvincePolicyApprovedPrice />
        </Grid>
      )}
      {value === "4" && (
        <Grid container xs={12} justifyContent="center" alignItems="center">
          <ManageEvacuations />
        </Grid>
      )}
    </Grid>
  );
};
