import { useContext, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  Autocomplete,
  Button,
  CircularProgress,
  FormControl,
  FormControlLabel,
  Grid,
  MenuItem,
  Radio,
  RadioGroup,
  Select,
  TextField,
  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 { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { getFaUserRole } from "../../../../utils/getFaUserRole";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

export const AssignSubUserModal = ({ device, onSuccess }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [options, setOptions] = useState([]);
  const [selectedUser, setSelectedUser] = useState(null);
  const [selectedAccessLevel, setSelectedAccessLevel] = useState("");
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [fetchError, setFetchError] = useState("");
  const [userType, setUserType] = useState("delegate");
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  useEffect(() => {
    let isMounted = true;

    const fetchUsers = async () => {
      setLoading(true);
      setFetchError("");
      setSelectedUser(null);
      setSelectedAccessLevel("");
      try {
        let response;
        const role = getRoleFromUrl();

        if (userType === "delegate") {
          response = await axios.get(
            `/get_representatives/?role=${role}${
              checkPathStartsWith("slaughter") || checkPathStartsWith("steward")
                ? `&role_key=${selectedSubUser?.key}`
                : ""
            }`
          );
        } else {
          response = await axios.get(
            `/get_dispensers/?role=${role}${
              checkPathStartsWith("slaughter") || checkPathStartsWith("steward")
                ? `&role_key=${selectedSubUser?.key}`
                : ""
            }`
          );
        }

        if (isMounted) {
          const rawOptions = Array.isArray(response?.data?.results)
            ? response?.data?.results
            : Array.isArray(response?.data)
            ? response?.data
            : Array.isArray(response?.data?.data)
            ? response?.data?.data
            : Array.isArray(response)
            ? response
            : [];

          // Normalize the data - both delegates and dispensers have the same structure
          const normalizedOptions = rawOptions.map((item) => {
            const fullname = item?.fullname || "-";
            const mobile = item?.mobile || "";
            const mobileLabel = mobile ? ` (${mobile})` : "";
            const label = `${fullname}${mobileLabel}`;

            return {
              ...item,
              label: label || "-",
            };
          });

          setOptions(normalizedOptions);
        }
      } catch (error) {
        if (isMounted) {
          setFetchError("دریافت لیست کاربران با خطا مواجه شد.");
          console.error("Error fetching users:", error);
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    fetchUsers();

    return () => {
      isMounted = false;
    };
  }, [userType, selectedSubUser?.key]);

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

  const getSubAccessLevels = (user) => {
    if (!user) return [];

    const subAccessLevels = [];

    // Common excluded boolean fields that are not access levels
    const excludedFields = [
      "active",
      "trash",
      "deleted",
      "isActive",
      "isDeleted",
    ];

    // Get all boolean fields that represent sub access levels
    // These are fields in the object that are boolean and indicate sub access levels
    Object.keys(user).forEach((key) => {
      if (typeof user[key] === "boolean" && user[key] === true) {
        // Exclude common boolean fields that aren't access levels
        if (!excludedFields.includes(key.toLowerCase())) {
          // Use getFaUserRole to get the Persian translation
          const translatedLabel = getFaUserRole(key);
          subAccessLevels.push({
            key: key,
            label: translatedLabel || key,
          });
        }
      }
    });

    return subAccessLevels;
  };

  const handleSubmit = async () => {
    if (!selectedUser) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        severity: "error",
        msg: "لطفاً یک کاربر را انتخاب کنید.",
      });
      return;
    }

    if (!device?.key && !device?.id) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        severity: "error",
        msg: "شناسه دستگاه یافت نشد. لطفاً دوباره تلاش کنید.",
      });
      return;
    }

    setSubmitting(true);
    try {
      const payload = {
        key: device?.key || device?.id,
        recipient_type:
          userType === "delegate" ? "representative" : "dispenser",
        recipient_key: selectedUser?.key || selectedUser?.id,
      };

      await axios.put("/user-pos-machine/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);
    }
  };

  const selectedUserSubAccessLevels = selectedUser
    ? getSubAccessLevels(selectedUser)
    : [];

  return (
    <Grid
      container
      direction="column"
      gap={SPACING.SMALL}
      width="100%"
      alignItems="stretch"
      sx={{ minWidth: 400 }}
    >
      <Typography variant="body2">
        دستگاه انتخاب شده:{" "}
        {device?.serial ||
          device?.pos_unique_id ||
          device?.pos_id ||
          device?.posId ||
          "-"}
      </Typography>
      <LabelField label="نوع کاربر">
        <FormControl fullWidth>
          <RadioGroup
            row
            sx={{ gap: 2 }}
            value={userType}
            onChange={(e) => setUserType(e.target.value)}
          >
            <FormControlLabel
              value="delegate"
              control={<Radio />}
              label="نماینده‌ها"
            />
            <FormControlLabel
              value="dispenser"
              control={<Radio />}
              label="پخش‌کنندگان"
            />
          </RadioGroup>
        </FormControl>
      </LabelField>
      {loading ? (
        <Grid container justifyContent="center">
          <CircularProgress size={24} />
        </Grid>
      ) : (
        <Autocomplete
          disablePortal
          fullWidth
          size="small"
          options={options}
          value={selectedUser}
          loading={loading}
          loadingText="در حال دریافت..."
          noOptionsText="موردی یافت نشد."
          onChange={(event, value) => {
            setSelectedUser(value);
            setSelectedAccessLevel("");
          }}
          isOptionEqualToValue={(option, value) =>
            option?.key === value?.key || option?.id === value?.id
          }
          getOptionLabel={(option) => option?.label || ""}
          renderOption={(props, option) => {
            if (!option) return null;
            return (
              <li {...props} key={option?.key || option?.id}>
                <Grid container direction="column">
                  <Typography variant="body2" fontWeight={600}>
                    {option?.label || "-"}
                  </Typography>
                  {option?.city && (
                    <Typography variant="caption" color="text.secondary">
                      {option.city}
                    </Typography>
                  )}
                </Grid>
              </li>
            );
          }}
          renderInput={(params) => (
            <TextField
              {...params}
              label="انتخاب کاربر"
              placeholder="نام یا شماره تماس"
              InputProps={{
                ...params.InputProps,
                endAdornment: (
                  <>
                    {loading ? (
                      <CircularProgress color="inherit" size={16} />
                    ) : null}
                    {params.InputProps.endAdornment}
                  </>
                ),
              }}
            />
          )}
        />
      )}
      {fetchError && (
        <Typography variant="caption" color="error">
          {fetchError}
        </Typography>
      )}
      {selectedUser && selectedUserSubAccessLevels.length > 0 && (
        <LabelField label="سطح دسترسی فرعی">
          <Select
            fullWidth
            size="small"
            value={selectedAccessLevel}
            onChange={(e) => setSelectedAccessLevel(e.target.value)}
            displayEmpty
          >
            <MenuItem value="">
              <em>انتخاب سطح دسترسی</em>
            </MenuItem>
            {selectedUserSubAccessLevels.map((level) => (
              <MenuItem key={level.key} value={level.key}>
                {level.label}
              </MenuItem>
            ))}
          </Select>
        </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={!selectedUser || submitting || loading}
        >
          {submitting ? "در حال ثبت..." : "ثبت"}
        </Button>
      </Grid>
    </Grid>
  );
};
