import { useEffect, useState } from "react";
import { useDispatch } 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 { Button, TextField, Autocomplete } from "@mui/material";
import { RiSearchLine } from "react-icons/ri";
import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable";
import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl";
import { formatJustDate, formatTime } from "../../../../utils/formatTime";

export const PspActiveSession = () => {
  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) => {
    let response;
    dispatch(LOADING_START());

    let url = `report-pos-device_session/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}`;
    if (selectedCompany) {
      url += `&company=${selectedCompany}`;
    }
    response = await axios.get(url);

    dispatch(LOADING_END());
    setData(response.data.results);
    setTotalRows(response.data.count);
  };

  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) => {
      return [
        page === 1 ? i + 1 : i + perPage * (page - 1) + 1,
        item?.pos?.posCompany,
        `${item?.pos?.userInfo?.type} (${item?.pos?.userInfo?.name})`,
        `${item?.pos?.userInfo?.fullname} (${item?.pos?.userInfo?.mobile})`,
        item?.pos?.userInfo?.nationalCode,
        item?.pos?.posId,
        item?.password,
        item?.name,
        formatJustDate(item?.sessionCreateDate),
        formatTime(item?.sessionLastSeenDate),
        item?.active ? "فعال" : "غیرفعال",
      ];
    });

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

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

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

  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="start"
        gap={SPACING.SMALL}
      >
        {getRoleFromUrl() !== "PosCompany" && (
          <Autocomplete
            size="small"
            style={{ minWidth: 210 }}
            disablePortal
            id="session"
            options={
              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>
  );

  return (
    <Grid container xs={12} justifyContent="center" alignItems="center" gap={2}>
      {tableTitle}
      <ResponsiveTable
        data={tableData}
        columns={[
          "ردیف",
          "شرکت پرداختی",
          "نام واحد",
          "نام شخص",
          "کدملی",
          "کلید اتصال",
          "کلمه عبور امنیتی",
          "نام دستگاه",
          "اولین ورود",
          "آخرین بازدید",
          "وضعیت",
        ]}
        handlePageChange={handlePageChange}
        totalRows={totalRows}
        page={page}
        perPage={perPage}
        handlePerRowsChange={handlePerRowsChange}
        title="نشست های فعال"
      />
    </Grid>
  );
};
