import * as React from "react";
import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  AccordionDetails,
  AccordionSummary,
  Accordion,
  Skeleton,
  Radio,
  Box,
  Typography,
  TextField,
  Button,
  Table,
  TableHead,
  TableBody,
  TableCell,
  TableRow,
} from "@mui/material";
import { GridSelectionModel } from "@mui/x-data-grid";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";

import ConditionalRender from "@root/pages/Setting/ConditionalRender";
import ModalUser from "@root/pages/dashboard/ModalUser";
import ServiceUsersDG from "./ServiceUsersDG";
import { useUsers, useManagers, useAdmins } from "@root/api/user/swr";
import { getRoles } from "@root/api/privilegies";

import { getRoles_mock, TMockData } from "../../../api/roles";

import theme from "../../../theme";

type Pages = {
  adminPage: number;
  managerPage: number;
  userPage: number;
};

type PagesSize = {
  adminPageSize: number;
  managerPageSize: number;
  userPageSize: number;
};

const Users: React.FC = () => {
  const radioboxes = ["admin", "manager", "user"];

  const [selectedValue, setSelectedValue] = React.useState("admin");

  const navigate = useNavigate();

  const [mockData, setMockData] = React.useState<TMockData>([]);

  const handleChangeData = () => {
    getRoles_mock().then((mockdata) => {
      setMockData(mockdata);
      setAccordionText(mockdata[0].desc || "");
    });
  };

  const [accordionState, setAccordionState] = React.useState<boolean>(true);
  const [accordionText, setAccordionText] = React.useState<string>("");

  const handleChange = (value: string) => {
    setSelectedValue(value);
    setAccordionText(mockData.find(({ name }) => name === value)?.desc || "");

    if (selectedValue === "manager") {
    }
  };

  const handleToggleAccordion = () => {
    setAccordionState(!accordionState);
  };

  const [roles, setRoles] = React.useState<TMockData>([]);

  const [page, setPage] = useState<Pages>({
    adminPage: 0,
    managerPage: 0,
    userPage: 0,
  });
  const [pageSize, setPageSize] = useState<PagesSize>({
    adminPageSize: 10,
    managerPageSize: 10,
    userPageSize: 10,
  });
  const [openUserModal, setOpenUserModal] = useState<boolean>(false);
  const [activeUserId, setActiveUserId] = useState<string>("");

  const { userId } = useParams();
  const { data: adminData, adminPages } = useAdmins(
    page.adminPage + 1,
    pageSize.adminPageSize
  );
  const { data: managerData, managerPages } = useManagers(
    page.managerPage + 1,
    pageSize.managerPageSize
  );
  const { data: userData, userPagesCount } = useUsers(
    page.userPage + 1,
    pageSize.userPageSize
  );

  useEffect(() => {
    handleChangeData();
  }, []);

  useEffect(() => {
    if (userId) {
      setActiveUserId(userId);
      setOpenUserModal(true);

      return;
    }

    setActiveUserId("");
    setOpenUserModal(false);
  }, [userId]);

  useEffect(() => {
    getRoles().then(([rolesResponse]) => {
      if (rolesResponse) {
        setRoles(rolesResponse);
      }
    });
  }, [selectedValue]);

  const [selectedTariffs, setSelectedTariffs] = useState<GridSelectionModel>(
    []
  );
  return (
    <React.Fragment>
      <Button
        variant="text"
        onClick={() => navigate("/modalAdmin")}
        sx={{
          width: "84%",
          display: "flex",
          flexDirection: "column",
          justifyContent: "center",
          alignItems: "center",
          marginBottom: "35px",
          border: "2px solid",
          fontWeight: "normal",
          borderColor: theme.palette.golden.main,
          color: theme.palette.secondary.main,
          "&:hover": {
            backgroundColor: theme.palette.menu.main,
          },
        }}
      >
        ИНФОРМАЦИЯ О ПРОЕКТЕ
      </Button>

      <Accordion
        sx={{
          width: "84%",
          backgroundColor: theme.palette.content.main,
        }}
        expanded={accordionState}
      >
        <AccordionSummary
          sx={{ display: "flex" }}
          onClick={handleToggleAccordion}
          expandIcon={
            <ExpandMoreIcon sx={{ color: theme.palette.secondary.main }} />
          }
          aria-controls="panel1a-content"
          id="panel1a-header"
        >
          <Typography
            sx={{
              width: "100%",
              color: theme.palette.secondary.main,
            }}
          >
            {accordionText}
          </Typography>
        </AccordionSummary>
        <AccordionDetails sx={{overflowX: "auto"}}>
          <Table
            sx={{
              width: "100%",
              border: "2px solid",
              borderColor: theme.palette.secondary.main,
            }}
            aria-label="simple table"
          >
            <TableHead>
              <TableRow
                sx={{
                  borderBottom: "2px solid",
                  borderColor: theme.palette.grayLight.main,
                  height: "100px",
                }}
              >
                <TableCell>
                  <Typography
                    variant="h4"
                    sx={{
                      color: theme.palette.secondary.main,
                    }}
                  >
                    Имя
                  </Typography>
                </TableCell>
                <TableCell>
                  <Typography
                    variant="h4"
                    sx={{
                      color: theme.palette.secondary.main,
                    }}
                  >
                    Описание
                  </Typography>
                </TableCell>
                <TableCell>
                  <Typography
                    variant="h4"
                    sx={{
                      color: theme.palette.secondary.main,
                    }}
                  >
                    Отобразить
                  </Typography>
                </TableCell>
              </TableRow>
            </TableHead>

            <TableBody>
              {mockData.length ? (
                mockData.map(function (item, index) {
                  return (
                    <TableRow
                      sx={{
                        borderTop: "2px solid",
                        borderColor: theme.palette.grayLight.main,
                        height: "100px",
                        cursor: "pointer",
                      }}
                      key={item.key}
                      onClick={() => handleChange(radioboxes[index])}
                    >
                      <TableCell>
                        <Typography
                          sx={{
                            color: theme.palette.secondary.main,
                          }}
                        >
                          {item.name}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Typography
                          sx={{
                            color: theme.palette.secondary.main,
                          }}
                        >
                          {item.desc}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Radio
                          checked={selectedValue === radioboxes[index]}
                          value={radioboxes[index]}
                          sx={{
                            "&, &.Mui-checked": {
                              color: theme.palette.secondary.main,
                            },
                          }}
                        />
                      </TableCell>
                    </TableRow>
                  );
                })
              ) : (
                <TableRow
                  sx={{
                    borderTop: "2px solid",
                    borderColor: theme.palette.grayLight.main,
                    height: "100px",
                  }}
                >
                  <TableCell colSpan={3}>
                    <Skeleton
                      variant="rectangular"
                      sx={{
                        width: "100%",
                        minWidth: "100%",
                        minHeight: "200px",
                        marginTop: "15px",
                        marginBottom: "15px",
                      }}
                    />
                  </TableCell>
                </TableRow>
              )}
            </TableBody>
          </Table>
        </AccordionDetails>
      </Accordion>

      <Box
        sx={{
          width: "90%",
          marginTop: "35px",
        }}
      >
        <Box sx={{ display: "flex" }}>
          <TextField
            id="standard-basic"
            label="id"
            variant="filled"
            color="secondary"
            sx={{
              width: "80%",
            }}
            InputProps={{
              style: {
                backgroundColor: theme.palette.content.main,
                color: theme.palette.secondary.main,
                borderBottom: "1px solid",
                borderColor: theme.palette.grayLight.main,
              },
            }}
            InputLabelProps={{
              style: {
                color: theme.palette.secondary.main,
              },
            }}
          />
          <Box
            sx={{
              display: "flex",
              justifyContent: "center",
              maxWidth: "317px",
              width: "100%",
            }}
          >
            <Button
              variant="text"
              sx={{
                backgroundColor: theme.palette.content.main,
                color: theme.palette.secondary.main,
                // width: "20%",
                "&:hover": {
                  backgroundColor: theme.palette.content.main,
                },
              }}
            >
              НАЙТИ
            </Button>
          </Box>
        </Box>

        <Box sx={{ display: "flex" }}>
          <TextField
            id="standard-basic"
            label="mail"
            variant="filled"
            color="secondary"
            sx={{
              width: "80%",
            }}
            InputProps={{
              style: {
                backgroundColor: theme.palette.content.main,
                color: theme.palette.secondary.main,
                borderBottom: "1px solid",
                borderColor: theme.palette.grayLight.main,
              },
            }}
            InputLabelProps={{
              style: {
                color: theme.palette.secondary.main,
              },
            }}
          />
          <Box
            sx={{
              display: "flex",
              justifyContent: "center",
              maxWidth: "317px",
              width: "100%",
            }}
          >
            <Button
              variant="text"
              sx={{
                backgroundColor: theme.palette.content.main,
                color: theme.palette.secondary.main,
                width: "20%",
                "&:hover": {
                  backgroundColor: theme.palette.content.main,
                },
              }}
            >
              СБРОСИТЬ
            </Button>
          </Box>
        </Box>
      </Box>
      <Box
        component="section"
        sx={{
          width: "90%",
          mt: "45px",
          display: "flex",
          justifyContent: "center",
        }}
      >
        <ConditionalRender
          isLoading={false}
          role={selectedValue}
          childrenAdmin={
            <ServiceUsersDG
              users={adminData?.users.length ? adminData.users : []}
              page={page.adminPage}
              setPage={(adminPage) =>
                setPage((pages) => ({ ...pages, adminPage }))
              }
              pagesCount={adminPages}
              pageSize={pageSize.adminPageSize}
              handleSelectionChange={setSelectedTariffs}
              onPageSizeChange={(adminPageSize) =>
                setPageSize((pageSize) => ({ ...pageSize, adminPageSize }))
              }
            />
          }
          childrenManager={
            <ServiceUsersDG
              users={managerData?.users.length ? managerData.users : []}
              page={page.managerPage}
              setPage={(managerPage) =>
                setPage((pages) => ({ ...pages, managerPage }))
              }
              pagesCount={managerPages}
              pageSize={pageSize.managerPageSize}
              handleSelectionChange={setSelectedTariffs}
              onPageSizeChange={(managerPageSize) =>
                setPageSize((pageSize) => ({ ...pageSize, managerPageSize }))
              }
            />
          }
          childrenUser={
            <ServiceUsersDG
              users={userData?.users.length ? userData.users : []}
              page={page.userPage}
              setPage={(userPage) =>
                setPage((pages) => ({ ...pages, userPage }))
              }
              pagesCount={userPagesCount}
              pageSize={pageSize.userPageSize}
              handleSelectionChange={setSelectedTariffs}
              onPageSizeChange={(userPageSize) =>
                setPageSize((pageSize) => ({ ...pageSize, userPageSize }))
              }
            />
          }
        />
      </Box>
      <ModalUser
        open={openUserModal}
        userId={activeUserId}
        onClose={() => {
          setOpenUserModal(false);
          navigate(-1);
        }}
      />
    </React.Fragment>
  );
};

export default Users;
