import React, { useContext, useState } from "react";
import { AppContext } from "../../../../contexts/AppContext";
import { Grid } from "../../../../components/grid/Grid";
import { Button, Switch, TextField, Typography } from "@mui/material";
import { provinceUpdateKillerIdentityService } from "../../services/province-update-killer-identity";
import { useDispatch } from "react-redux";

export const ProvinceManageWarehouseLimitation = ({ item, fetchdata }) => {
  const [openNotif] = useContext(AppContext);

  const dispatch = useDispatch();

  // Weight limitation states
  const [weightLimitEnabled, setWeightLimitEnabled] = useState(
    item?.wareHouseRemainingWeightLimitationStatus || false
  );
  const [weightLimit, setWeightLimit] = useState(
    item?.wareHouseRemainingWeightLimitation || ""
  );

  // Percent limitation states
  const [percentLimitEnabled, setPercentLimitEnabled] = useState(
    item?.wareHouseRemainingPercentLimitationStatus || false
  );
  const [percentLimit, setPercentLimit] = useState(
    item?.wareHouseRemainingPercentLimitation || ""
  );

  const handleWeightToggle = () => {
    setWeightLimitEnabled(!weightLimitEnabled);
  };

  const handlePercentToggle = () => {
    setPercentLimitEnabled(!percentLimitEnabled);
  };

  const handleSubmit = () => {
    dispatch(
      provinceUpdateKillerIdentityService({
        kill_house_key: item?.key,
        ware_house_remaining_weight_limitation_status: weightLimitEnabled,
        ware_house_remaining_weight_limitation: weightLimitEnabled
          ? weightLimit
          : 0,
        ware_house_remaining_percent_limitation_status: percentLimitEnabled,
        ware_house_remaining_percent_limitation: percentLimitEnabled
          ? percentLimit
          : 0,
      })
    ).then((r) => {
      if (r.payload.error) {
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: r.payload.error,
          severity: "error",
        });
      } else {
        fetchdata();
        openNotif({
          vertical: "top",
          horizontal: "center",
          msg: "محدودیت‌های انبار با موفقیت ویرایش شد.",
          severity: "success",
        });
      }
    });
  };

  return (
    <Grid
      container
      direction="column"
      alignItems="flex-start"
      width="100%"
      sx={{ px: { xs: 1, sm: 0 } }}
    >
      <Grid item width="100%" mb={2}>
        <Typography
          variant="h6"
          sx={{
            fontSize: { xs: "1rem", sm: "1rem" },
            fontWeight: "bold",
          }}
        >
          محدودیت سقف انبار
        </Typography>
      </Grid>

      {/* Weight Limitation Section */}
      <Grid
        item
        container
        direction="column"
        spacing={{ xs: 2, sm: 2 }}
        width="100%"
        mb={2}
        px={1}
      >
        <Grid
          item
          container
          direction="row"
          alignItems="center"
          flexWrap="wrap"
          sx={{ gap: 2 }}
        >
          <Grid item>
            <Switch
              checked={weightLimitEnabled}
              onChange={handleWeightToggle}
              inputProps={{ "aria-label": "محدودیت وزن انبار" }}
              size="small"
            />
          </Grid>
          <Grid item xs>
            <Typography
              sx={{
                fontSize: { xs: "0.625rem", sm: "0.875rem" },
              }}
            >
              محدودیت مانده انبار
            </Typography>
          </Grid>
        </Grid>

        {weightLimitEnabled && (
          <Grid
            item
            container
            spacing={{ xs: 1, sm: 2 }}
            alignItems="stretch"
            mb={2}
          >
            <Grid item xs={12} mt={2}>
              <TextField
                fullWidth
                label="حداکثر وزن باقی مانده انبار (کیلوگرم)"
                type="number"
                value={weightLimit}
                onChange={(e) => setWeightLimit(e.target.value)}
                size="small"
                inputProps={{ min: 0 }}
                sx={{
                  "& .MuiInputLabel-root": {
                    fontSize: { xs: "0.875rem", sm: "1rem" },
                  },
                  "& .MuiInputBase-input": {
                    fontSize: { xs: "0.875rem", sm: "1rem" },
                  },
                }}
              />
            </Grid>
          </Grid>
        )}
      </Grid>

      {/* Percent Limitation Section */}
      <Grid
        item
        container
        direction="column"
        spacing={{ xs: 1.5, sm: 2 }}
        width="100%"
        px={1}
      >
        <Grid
          item
          container
          direction="row"
          alignItems="center"
          flexWrap="wrap"
          sx={{ gap: 2 }}
        >
          <Grid item>
            <Switch
              checked={percentLimitEnabled}
              onChange={handlePercentToggle}
              inputProps={{ "aria-label": "محدودیت درصد انبار" }}
              size="small"
            />
          </Grid>
          <Grid item xs>
            <Typography
              sx={{
                fontSize: { xs: "0.625rem", sm: "0.875rem" },
              }}
            >
              محدودیت مانده کشتار روزانه
            </Typography>
          </Grid>
        </Grid>

        {percentLimitEnabled && (
          <Grid
            item
            container
            spacing={{ xs: 1, sm: 2 }}
            mt={2}
            alignItems="stretch"
            xs={12}
          >
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="درصد وزن باقی مانده روزانه انبار"
                type="number"
                value={percentLimit}
                onChange={(e) => setPercentLimit(e.target.value)}
                size="small"
                inputProps={{ min: 0, max: 100 }}
                sx={{
                  "& .MuiInputLabel-root": {
                    fontSize: { xs: "0.875rem", sm: "1rem" },
                  },
                  "& .MuiInputBase-input": {
                    fontSize: { xs: "0.875rem", sm: "1rem" },
                  },
                }}
              />
            </Grid>
          </Grid>
        )}
      </Grid>

      {/* Submit Button */}
      <Grid item width="100%" mt={4}>
        <Button
          variant="contained"
          onClick={handleSubmit}
          fullWidth
          disabled={
            (weightLimitEnabled && (!weightLimit || weightLimit <= 0)) ||
            (percentLimitEnabled &&
              (!percentLimit || percentLimit <= 0 || percentLimit > 100))
          }
          sx={{
            fontSize: { xs: "0.875rem" },
            py: { xs: 1.5, sm: 1 },
          }}
        >
          ثبت اطلاعات
        </Button>
      </Grid>
    </Grid>
  );
};
