import {
  mdiAccountMultiple,
  mdiCog,
  mdiCrowd,
  mdiFamilyTree,
  mdiHumanMaleFemale,
} from "@mdi/js";
import Icon from "@mdi/react";
import HomeIcon from "@mui/icons-material/Home";
import {
  Box,
  Divider,
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  ListSubheader,
} from "@mui/material";
import React from "react";
import { Outlet, useLocation, useParams } from "react-router-dom";
import { Family, FamilyApi } from "../api/FamilyApi";
import { AsyncWidget } from "./AsyncWidget";
import { RouterLink } from "./RouterLink";

interface FamilyContext {
  family: Family;
  reloadFamilyInfo: () => void;
}

const FamilyContextK = React.createContext<FamilyContext | null>(null);

export function BaseFamilyRoute(): React.ReactElement {
  const { familyId } = useParams();

  const [family, setFamily] = React.useState<null | Family>(null);

  const loadKey = React.useRef(1);

  const load = async () => {
    setFamily(await FamilyApi.GetSingle(Number(familyId)));
  };

  const onReload = () => {
    loadKey.current += 1;
    setFamily(null);
  };

  return (
    <AsyncWidget
      ready={family != null}
      loadKey={`${familyId}-${loadKey}`}
      load={load}
      errMsg="Échec du chargement des informations de la famille !"
      build={() => (
        <FamilyContextK.Provider
          value={{
            family: family!,
            reloadFamilyInfo: onReload,
          }}
        >
          <Box sx={{ display: "flex", flex: "2" }}>
            <List component="nav">
              <FamilyLink icon={<HomeIcon />} label="Accueil" uri="" />

              <FamilyLink
                icon={<Icon path={mdiCrowd} size={1} />}
                label="Membres"
                uri="members"
              />

              <FamilyLink
                icon={<Icon path={mdiHumanMaleFemale} size={1} />}
                label="Couples"
                uri="couples"
              />

              <FamilyLink
                icon={<Icon path={mdiFamilyTree} size={1} />}
                label="Arbre"
                uri="tree"
              />

              <Divider sx={{ my: 1 }} />
              <ListSubheader component="div" inset>
                Administration
              </ListSubheader>

              <FamilyLink
                icon={<Icon path={mdiAccountMultiple} size={1} />}
                label="Utilisateurs"
                uri="users"
              />

              <FamilyLink
                icon={<Icon path={mdiCog} size={1} />}
                label="Paramètres"
                uri="settings"
              />
            </List>

            <Box
              component="main"
              sx={{
                backgroundColor: (theme) =>
                  theme.palette.mode === "light"
                    ? theme.palette.grey[100]
                    : theme.palette.grey[900],
                flexGrow: 1,
                overflow: "auto",
                padding: "20px",
              }}
            >
              <Outlet />
            </Box>
          </Box>
        </FamilyContextK.Provider>
      )}
    />
  );
}

export function useFamily(): FamilyContext {
  return React.useContext(FamilyContextK)!;
}

function FamilyLink(p: {
  icon: React.ReactElement;
  uri: string;
  label: string;
}): React.ReactElement {
  const family = useFamily();
  const location = useLocation();
  const link = family.family.URL(p.uri);

  return (
    <RouterLink to={link}>
      <ListItemButton selected={link === location.pathname}>
        <ListItemIcon>{p.icon}</ListItemIcon>
        <ListItemText primary={p.label} />
      </ListItemButton>
    </RouterLink>
  );
}
