import { useContext, useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import {
  LOADING_END,
  LOADING_START,
  CLOSE_MODAL,
  OPEN_MODAL,
  DRAWER,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import {
  Autocomplete,
  Button,
  CircularProgress,
  IconButton,
  List,
  ListItem,
  ListItemIcon,
  ListItemButton,
  ListItemText,
  Popover,
  Switch,
  TextField,
  Typography,
  Box,
} from "@mui/material";
import { RiSearchLine } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatJustDate } from "../../../../utils/formatTime";
import TuneIcon from "@mui/icons-material/Tune";
import PersonAddAlt1RoundedIcon from "@mui/icons-material/PersonAddAlt1Rounded";
import SwapHorizRoundedIcon from "@mui/icons-material/SwapHorizRounded";
import AddRoundedIcon from "@mui/icons-material/AddRounded";
import { AppContext } from "../../../../contexts/AppContext";
import { BackButton } from "../../../../components/back-button/BackButton";

const PspDevicesV2 = () => {
  const [data, setData] = useState([]);
  const [totalRows, setTotalRows] = useState(0);
  const [perPage, setPerPage] = useState(10);
  const [textValue, setTextValue] = useState("");
  const [page, setPage] = useState(1);
  const [tableData, setTableData] = useState([]);
  const [companies, setCompanies] = useState([]);
  const [selectedCompany, setSelectedCompany] = useState("");
  const dispatch = useDispatch();

  const fetchCompanies = async () => {
    try {
      dispatch(LOADING_START());
      const response = await axios.get(
        `/get_all_pos_company/?role=${getRoleFromUrl()}`
      );
      setCompanies(response.data);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching companies:", error);
      dispatch(LOADING_END());
    }
  };

  const fetchApiData = async (page) => {
    try {
      dispatch(LOADING_START());
      let url = `/user-pos-machine/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}`;
      if (selectedCompany) {
        url += `&company=${selectedCompany}`;
      }
      const response = await axios.get(url);

      setData(response.data?.results || []);
      setTotalRows(response.data?.count || 0);
    } catch (error) {
      console.error("Error fetching devices:", error);
    } finally {
      dispatch(LOADING_END());
    }
  };

  const handlePageChange = (page) => {
    fetchApiData(page);
    setPage(page);
  };

  const handlePerRowsChange = (perRows) => {
    setPerPage(perRows);
    setPage(1);
  };

  const handleTextChange = (event) => {
    setTextValue(event.target.value);
  };
  // const clearFilters = () => {
  //   setSelectedCompany("");
  //   setTextValue("");
  //   setPage(1);
  //   fetchApiData(1);
  // };

  useEffect(() => {
    const d = data?.map((item, i) => {
      const owner = item?.owner || {};
      const posCompany = item?.pos_company || {};
      const hasOwner = !!item?.owner;
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        posCompany?.name || "-",
        item?.serial ?? "-",
        item?.receiverNumber ?? "-",
        item?.terminalNumber ?? "-",
        item?.password ?? "-",
        item?.posUniqueId || item?.posId || "-",
        owner?.fullname ? `${owner?.fullname} (${owner?.mobile ?? "-"})` : "-",
        owner?.nationalId || owner?.nationalCode || "-",
        item?.createDate ? formatJustDate(item?.createDate) : "-",
        item?.active ? "فعال" : "غیرفعال",
        <DeviceOperations
          key={item?.id || item?.key || `device-${i}`}
          device={item}
          hasOwner={hasOwner}
          onOwnerAssigned={() => {
            fetchApiData(page);
          }}
        />,
      ];
    });

    setTableData(d);
  }, [data, page, perPage]);

  useEffect(() => {
    fetchCompanies();
  }, [dispatch]);

  useEffect(() => {
    fetchApiData(page);
  }, [selectedCompany, perPage]);

  const handleSubmit = async (event) => {
    event.preventDefault();
    fetchApiData(1);
  };

  const handleDeviceCreated = () => {
    setPage(1);
    fetchApiData(1);
  };

  const handleOpenCreateDevice = () => {
    const isMobile = window.innerWidth <= 600;
    dispatch(
      DRAWER({
        title: "ایجاد دستگاه",
        right: !isMobile,
        bottom: isMobile,
        content: <CreateDeviceDrawer onSuccess={handleDeviceCreated} />,
      })
    );
  };

  const tableTitle = (
    <Grid
      container
      alignItems="center"
      justifyContent="space-between"
      gap={2}
      mb={1}
      padding={2}
      width="100%"
    >
      <Grid
        container
        width="100%"
        alignItems="center"
        justifyContent="space-between"
        gap={SPACING.SMALL}
      >
        <Grid
          container
          alignItems="center"
          gap={SPACING.SMALL}
          xs={12}
          md="auto"
        >
          {getRoleFromUrl() !== "PosCompany" && (
            <Autocomplete
              size="small"
              style={{ minWidth: 210 }}
              disablePortal
              id="session"
              options={
                Array.isArray(companies)
                  ? companies.map((i) => {
                      return {
                        data: i,
                        label: `${i?.name || ""}`,
                      };
                    })
                  : []
              }
              onChange={(event, value) => {
                setSelectedCompany(value?.data?.key);
              }}
              renderInput={(params) => (
                <TextField fullWidth {...params} label="انتخاب شرکت psp" />
              )}
            />
          )}

          <Grid container alignItems="center" gap={SPACING.SMALL}>
            <TextField
              size="small"
              autoComplete="off"
              label="جستجو"
              variant="outlined"
              style={{ width: 250 }}
              value={textValue}
              onChange={handleTextChange}
            />

            <Button
              type="submit"
              onClick={handleSubmit}
              endIcon={<RiSearchLine />}
            >
              جستجو
            </Button>
          </Grid>
        </Grid>

        <Grid container justifyContent="flex-end" xs={12} md="auto">
          <Button
            variant="contained"
            startIcon={<AddRoundedIcon />}
            onClick={handleOpenCreateDevice}
          >
            ایجاد دستگاه
          </Button>
        </Grid>
      </Grid>
    </Grid>
  );

  return (
    <Box display={"flex"} justifyContent="center">
      <Grid container xs={12} lg={10}>
        <BackButton />
        {tableTitle}
        <ResponsiveTable
          data={tableData}
          columns={[
            "ردیف",
            "شرکت پرداختی",
            "شماره سریال",
            "شماره پذیرنده",
            "شماره ترمینال",
            "کلمه عبور امنیتی",
            "کلید پوز",
            "مالک",
            "کدملی",
            "تاریخ ایجاد",
            "فعال / غیرفعال",
            "عملیات",
          ]}
          handlePageChange={handlePageChange}
          totalRows={totalRows}
          page={page}
          perPage={perPage}
          handlePerRowsChange={handlePerRowsChange}
          title="مدیریت دستگاه ها"
        />
      </Grid>
    </Box>
  );
};

const DeviceOperations = ({ device, hasOwner, onOwnerAssigned }) => {
  const [anchorEl, setAnchorEl] = useState(null);
  const [updatingStatus] = useState(false);
  const [localActive, setLocalActive] = useState(!!device?.active);
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);

  useEffect(() => {
    setLocalActive(!!device?.active);
  }, [device?.active]);

  const handleOpen = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleAddOwner = () => {
    handleClose();
    dispatch(
      OPEN_MODAL({
        title: hasOwner ? "تغییر مالک" : "افزودن مالک",
        width: "auto",
        content: (
          <AssignOwnerModal device={device} onSuccess={onOwnerAssigned} />
        ),
      })
    );
  };

  const open = Boolean(anchorEl);
  const id = open ? "device-operations-popover" : undefined;
  const actionLabel = hasOwner ? "تغییر مالک" : "افزودن مالک";
  const ActionIcon = hasOwner ? SwapHorizRoundedIcon : PersonAddAlt1RoundedIcon;
  const actionColor = hasOwner ? "warning.main" : "success.main";
  const deviceKey = device?.key || device?.id;

  const handleToggleActive = async (event) => {
    event.stopPropagation();
    event.preventDefault();

    if (!deviceKey) {
      openNotif({
        vertical: "top",
        horizontal: "center",
        severity: "error",
        msg: "شناسه دستگاه یافت نشد.",
      });
      return;
    }
  };

  return (
    <>
      <IconButton
        aria-describedby={id}
        color="primary"
        onClick={handleOpen}
        size="small"
      >
        <TuneIcon fontSize="small" />
      </IconButton>
      <Popover
        id={id}
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        anchorOrigin={{
          vertical: "bottom",
          horizontal: "right",
        }}
        transformOrigin={{
          vertical: "top",
          horizontal: "left",
        }}
      >
        <List sx={{ minWidth: 160, p: 0 }}>
          <ListItem
            sx={{
              px: 2,
              py: 1,
              display: "flex",
              alignItems: "center",
              gap: 1,
            }}
          >
            <ListItemText
              primary="وضعیت دستگاه"
              secondary={localActive ? "فعال" : "غیرفعال"}
            />
            <Switch
              edge="end"
              color="success"
              checked={localActive}
              onChange={handleToggleActive}
              disabled={updatingStatus || !deviceKey}
            />
          </ListItem>
          <ListItemButton onClick={handleAddOwner}>
            <ListItemIcon sx={{ minWidth: 36, color: actionColor }}>
              <ActionIcon fontSize="small" />
            </ListItemIcon>
            <ListItemText
              primary={actionLabel}
              primaryTypographyProps={{ sx: { color: actionColor } }}
            />
          </ListItemButton>
        </List>
      </Popover>
    </>
  );
};

const AssignOwnerModal = ({ device, onSuccess }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [options, setOptions] = useState([]);
  const [selectedOption, setSelectedOption] = useState(null);
  const [loading, setLoading] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [fetchError, setFetchError] = useState("");

  useEffect(() => {
    let isMounted = true;

    const fetchOwners = async () => {
      setLoading(true);
      setFetchError("");
      setSelectedOption(null);
      try {
        const response = await axios.get("/users_for_pos/");

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

          // Normalize the data
          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);
          setSelectedOption(
            normalizedOptions.find(
              (option) => option?.mobile === device?.owner?.mobile
            )
          );
        }
      } catch (error) {
        if (isMounted) {
          setFetchError("دریافت لیست کاربران با خطا مواجه شد.");
          console.error("Error fetching users:", error);
        }
      } finally {
        if (isMounted) {
          setLoading(false);
        }
      }
    };

    fetchOwners();

    return () => {
      isMounted = false;
    };
  }, [device]);

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

  const handleSubmit = async () => {
    if (!selectedOption) {
      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: "owner",
        recipient_key: selectedOption?.key || selectedOption?.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);
    }
  };

  return (
    <Grid
      container
      direction="column"
      gap={SPACING.SMALL}
      width="100%"
      alignItems="stretch"
    >
      <Typography variant="body2">
        دستگاه انتخاب شده:{" "}
        {device?.serial ||
          device?.posUniqueId ||
          device?.posId ||
          device?.pos_unique_id ||
          device?.pos_id ||
          "-"}
      </Typography>
      {loading ? (
        <Grid container justifyContent="center">
          <CircularProgress size={24} />
        </Grid>
      ) : (
        <Autocomplete
          disablePortal
          fullWidth
          size="small"
          options={options}
          value={selectedOption}
          groupBy={(option) => option?.group || ""}
          loading={loading}
          loadingText="در حال دریافت..."
          noOptionsText="موردی یافت نشد."
          onChange={(event, value) => setSelectedOption(value)}
          isOptionEqualToValue={(option, value) => option?.key === value?.key}
          getOptionLabel={(option) => option?.label || ""}
          renderOption={(props, option) => {
            if (!option) return null;
            return (
              <li {...props} key={option?.key}>
                <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>
      )}
      <Grid container justifyContent="flex-end" gap={SPACING.SMALL}>
        <Button
          variant="outlined"
          color="primary"
          onClick={handleCloseModal}
          disabled={submitting}
        >
          انصراف
        </Button>
        <Button
          variant="contained"
          onClick={handleSubmit}
          disabled={!selectedOption || submitting || loading}
        >
          {submitting ? "در حال ثبت..." : "ثبت"}
        </Button>
      </Grid>
    </Grid>
  );
};

const CreateDeviceDrawer = ({ onSuccess }) => {
  const dispatch = useDispatch();
  const [openNotif] = useContext(AppContext);
  const [values, setValues] = useState({
    receiver_number: "",
    terminal_number: "",
    password: "",
    serial: "",
  });
  const [errors, setErrors] = useState({});
  const [submitting, setSubmitting] = useState(false);

  const closeDrawer = () => {
    dispatch(DRAWER({ right: false, bottom: false, content: null }));
  };

  const handleChange = (event) => {
    const { name, value } = event.target;
    setValues((prev) => ({ ...prev, [name]: value }));
    if (errors[name]) {
      setErrors((prev) => ({ ...prev, [name]: "" }));
    }
  };

  const validate = () => {
    const newErrors = {};
    if (!values.receiver_number?.trim()) {
      newErrors.receiver_number = "وارد کردن شماره پذیرنده الزامی است.";
    }
    if (!values.terminal_number?.trim()) {
      newErrors.terminal_number = "وارد کردن شماره ترمینال الزامی است.";
    }
    if (!values.password?.trim()) {
      newErrors.password = "وارد کردن رمز عبور الزامی است.";
    }
    if (!values.serial?.trim()) {
      newErrors.serial = "وارد کردن سریال دستگاه الزامی است.";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    if (!validate()) {
      return;
    }

    setSubmitting(true);
    try {
      await axios.post("/new-pos-machine/", {
        receiver_number: values.receiver_number.trim(),
        terminal_number: values.terminal_number.trim(),
        password: values.password.trim(),
        serial: values.serial.trim(),
      });

      openNotif({
        vertical: "top",
        horizontal: "center",
        severity: "success",
        msg: "دستگاه با موفقیت ایجاد شد.",
      });

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

  return (
    <Grid
      component="form"
      onSubmit={handleSubmit}
      container
      direction="column"
      gap={SPACING.SMALL}
      width="100%"
      autoComplete="off"
      xs={12}
    >
      <TextField
        label="سریال دستگاه"
        name="serial"
        value={values.serial}
        onChange={handleChange}
        fullWidth
        error={Boolean(errors.serial)}
        helperText={errors.serial}
      />
      <TextField
        label="شماره پذیرنده"
        name="receiver_number"
        value={values.receiver_number}
        onChange={handleChange}
        fullWidth
        error={Boolean(errors.receiver_number)}
        helperText={errors.receiver_number}
      />
      <TextField
        label="شماره ترمینال"
        name="terminal_number"
        value={values.terminal_number}
        onChange={handleChange}
        fullWidth
        error={Boolean(errors.terminal_number)}
        helperText={errors.terminal_number}
      />
      <TextField
        label="رمز عبور"
        name="password"
        value={values.password}
        onChange={handleChange}
        fullWidth
        error={Boolean(errors.password)}
        helperText={errors.password}
      />
      <Grid
        container
        justifyContent="justify-between"
        gap={SPACING.SMALL}
        mt={SPACING.SMALL}
        xs={12}
      >
        <Button
          variant="outlined"
          color="primary"
          style={{
            width: "46%",
          }}
          onClick={closeDrawer}
          disabled={submitting}
        >
          انصراف
        </Button>
        <Button
          style={{
            width: "46%",
          }}
          variant="contained"
          type="submit"
          disabled={submitting}
        >
          {submitting ? "در حال ثبت..." : "ثبت"}
        </Button>
      </Grid>
    </Grid>
  );
};

export default PspDevicesV2;
