import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  LOADING_END,
  LOADING_START,
} from "../../../../lib/redux/slices/appSlice";
import axios from "axios";
import { Grid } from "../../../../components/grid/Grid";
import { SPACING } from "../../../../data/spacing";
import { BackButton } from "../../../../components/back-button/BackButton";
import { Autocomplete, Button, TextField, Box, Chip } 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 { getFaUserRole } from "../../../../utils/getFaUserRole";
import { DeviceOperations } from "./DeviceOperations";
import { Lock } from "@mui/icons-material";
import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith";

const GuildPspDevices = () => {
  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 [brands, setBrands] = useState([]);
  const [selectedBrand, setSelectedBrand] = useState("");
  const selectedSubUser = useSelector(
    (state) => state.userSlice.selectedSubUser
  );
  const dispatch = useDispatch();

  const fetchBrands = async () => {
    try {
      dispatch(LOADING_START());
      const response = await axios.get(
        `/get_all_pos_company/?role=${getRoleFromUrl()}${
          checkPathStartsWith("slaughter") || checkPathStartsWith("steward")
            ? `&role_key=${selectedSubUser?.key}`
            : ""
        }`
      );
      setBrands(response.data);
      dispatch(LOADING_END());
    } catch (error) {
      console.error("Error fetching brands:", error);
      dispatch(LOADING_END());
    }
  };

  const canDoAction = (item) => {
    if (item?.owner?.role?.includes("KillHouse")) {
      return getRoleFromUrl() === "KillHouse";
    }
    if (item?.owner?.includes("Steward")) {
      return getRoleFromUrl() === "Steward";
    }
    return false;
  };

  const fetchApiData = async (page) => {
    try {
      dispatch(LOADING_START());
      let url = `/user-pos-machine/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${
        checkPathStartsWith("slaughter") || checkPathStartsWith("steward")
          ? `&role_key=${selectedSubUser?.key}`
          : ""
      }&page=${page}&page_size=${perPage}`;
      if (selectedBrand) {
        url += `&company=${selectedBrand}`;
      }
      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);
  };

  useEffect(() => {
    const d = data?.map((item, i) => {
      const owner = item?.owner || {};
      const posCompany = item?.posCompany || {};

      // Format recipient information
      const recipientDisplay = item?.recipient
        ? `${item?.recipient?.firstName || ""} ${
            item?.recipient?.lastName || ""
          }`.trim() +
          (item?.recipient?.mobile
            ? ` (${item?.recipient?.mobile} - ${
                item?.recipient?.agentType === "dispenser"
                  ? "توزیع کننده"
                  : "نماینده"
              })`
            : "")
        : "-";

      // Format access_levels to display as chips only (filter out trash items)
      const activeAccessLevels = Array.isArray(item?.accessLevels)
        ? item.accessLevels.filter((level) => !level?.trash)
        : [];
      const accessLevelsDisplay =
        activeAccessLevels.length > 0 ? (
          <Grid container gap={0.5} flexWrap="wrap">
            {activeAccessLevels.map((level, idx) => (
              <Chip
                key={level?.key || idx}
                label={getFaUserRole(level?.name) || level?.name || "-"}
                size="small"
              />
            ))}
          </Grid>
        ) : (
          "-"
        );

      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) : "-",
        accessLevelsDisplay,
        recipientDisplay,
        item?.active ? "فعال" : "غیرفعال",
        canDoAction(item) ? (
          <DeviceOperations
            key={item?.id || item?.key || `device-${i}`}
            device={item}
          />
        ) : (
          <Lock sx={{ fontSize: 20, mt: 1, color: "gray" }} />
        ),
      ];
    });

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

  useEffect(() => {
    fetchBrands();
  }, [dispatch, selectedSubUser?.key]);

  useEffect(() => {
    fetchApiData(page);
  }, [selectedBrand, perPage, selectedSubUser?.key]);

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

  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"
        >
          <Autocomplete
            size="small"
            style={{ minWidth: 210 }}
            disablePortal
            id="brand"
            options={
              Array.isArray(brands)
                ? brands.map((i) => {
                    return {
                      data: i,
                      label: `${i?.name || ""}`,
                    };
                  })
                : []
            }
            onChange={(event, value) => {
              setSelectedBrand(value?.data?.key);
            }}
            renderInput={(params) => (
              <TextField fullWidth {...params} label="انتخاب برند دستگاه" />
            )}
          />

          <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>
    </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>
  );
};

export default GuildPspDevices;
