import { useContext, useState } from "react";
import { useDispatch } from "react-redux";
import {
  Button,
  Checkbox,
  FormControlLabel,
  Grid,
  Typography,
} from "@mui/material";
import axios from "axios";
import { AppContext } from "../../../../contexts/AppContext";
import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice";
import { LabelField } from "../../../../components/label-field/LabelField";
import { SPACING } from "../../../../data/spacing";
import { getFaUserRole } from "../../../../utils/getFaUserRole";

export const EditSubSectionsModal = ({ accessLevel, device, onSuccess }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [submitting, setSubmitting] = useState(false);
  const [values, setValues] = useState({
    in_province_sale: accessLevel?.in_province_sale || false,
    out_province_sale: accessLevel?.out_province_sale || false,
    cutting: accessLevel?.cutting || false,
    freezing: accessLevel?.freezing || false,
    warehouse: accessLevel?.warehouse || false,
    retail: accessLevel?.retail || false,
  });

  const handleCloseModal = () => {
    dispatch(CLOSE_MODAL());
  };

  const handleChange = (field) => (event) => {
    setValues((prev) => ({
      ...prev,
      [field]: event.target.checked,
    }));
  };

  const handleSubmit = async () => {
    if (!accessLevel?.key) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        severity: "error",
        msg: "شناسه سطح دسترسی یافت نشد. لطفاً دوباره تلاش کنید.",
      });
      return;
    }

    setSubmitting(true);
    try {
      const payload = {
        key: accessLevel.key,
        in_province_sale: values.in_province_sale,
        out_province_sale: values.out_province_sale,
        cutting: values.cutting,
        freezing: values.freezing,
        warehouse: values.warehouse,
        retail: values.retail,
      };

      await axios.put("/pos-access-level/0/", payload);

      openNotif({
        vertical: "top",
        horizontal: "center",
        severity: "success",
        msg: "زیربخش‌های سطح دسترسی با موفقیت ویرایش شد.",
      });

      if (onSuccess) {
        onSuccess();
      }
      handleCloseModal();
    } catch (error) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        severity: "error",
        msg:
          error?.response?.data?.result ||
          error?.response?.data?.detail ||
          "ویرایش زیربخش‌ها با خطا مواجه شد.",
      });
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <Grid
      container
      direction="column"
      gap={SPACING.SMALL}
      width="100%"
      alignItems="stretch"
      sx={{ minWidth: 400 }}
    >
      <Typography variant="body2">
        سطح دسترسی:{" "}
        {getFaUserRole(accessLevel?.name) || accessLevel?.name || "-"}
      </Typography>
      <Typography variant="body2">
        دستگاه:{" "}
        {device?.serial ||
          device?.pos_unique_id ||
          device?.pos_id ||
          device?.posId ||
          "-"}
      </Typography>
      <LabelField label="تنظیمات زیربخش‌ها">
        <Grid container p={1}>
          <Grid item xs={6}>
            <FormControlLabel
              control={
                <Checkbox
                  checked={values.in_province_sale}
                  onChange={handleChange("in_province_sale")}
                />
              }
              label="فروش داخل استان"
            />
          </Grid>
          <Grid item xs={6}>
            <FormControlLabel
              control={
                <Checkbox
                  checked={values.out_province_sale}
                  onChange={handleChange("out_province_sale")}
                />
              }
              label="فروش خارج استان"
            />
          </Grid>
          <Grid item xs={6}>
            <FormControlLabel
              control={
                <Checkbox
                  checked={values.cutting}
                  onChange={handleChange("cutting")}
                />
              }
              label="قطعه بندی"
            />
          </Grid>
          <Grid item xs={6}>
            <FormControlLabel
              control={
                <Checkbox
                  checked={values.freezing}
                  onChange={handleChange("freezing")}
                />
              }
              label="انجماد"
            />
          </Grid>
          <Grid item xs={6}>
            <FormControlLabel
              control={
                <Checkbox
                  checked={values.warehouse}
                  onChange={handleChange("warehouse")}
                />
              }
              label="انبار"
            />
          </Grid>
          <Grid item xs={6}>
            <FormControlLabel
              control={
                <Checkbox
                  checked={values.retail}
                  onChange={handleChange("retail")}
                />
              }
              label="خرده‌فروشی"
            />
          </Grid>
        </Grid>
      </LabelField>
      <Grid container justifyContent="flex-end" gap={SPACING.SMALL} mt={2}>
        <Button
          variant="outlined"
          color="primary"
          onClick={handleCloseModal}
          disabled={submitting}
        >
          انصراف
        </Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
          disabled={submitting}
        >
          {submitting ? "در حال ثبت..." : "ثبت"}
        </Button>
      </Grid>
    </Grid>
  );
};
