import { mdiCashMultiple, mdiHome, mdiInbox } from "@mdi/js";
import Icon from "@mdi/react";
import {
  Chip,
  Divider,
  List,
  ListItem,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  Typography,
} from "@mui/material";
import React from "react";
import { useLocation } from "react-router-dom";
import { useAccounts } from "../hooks/AccountsListProvider";
import { usePublicMode } from "../hooks/context_providers/PublicModeProvider";
import { AccountIconWidget } from "./AccountIconWidget";
import { AmountWidget } from "./AmountWidget";
import { RouterLink } from "./RouterLink";
import { useUnmatchedInboxEntriesCount } from "../hooks/UnmatchedInboxEntriesCountProvider";

export function MoneyNavList(): React.ReactElement {
  const publicMode = usePublicMode();
  const accounts = useAccounts();
  const unmatched = useUnmatchedInboxEntriesCount();
  return (
    <List
      dense
      component="nav"
      sx={{
        minWidth: "200px",
        backgroundColor: "background.paper",
      }}
    >
      <NavLink label="Home" uri="/" icon={<Icon path={mdiHome} size={1} />} />

      <NavLink
        label="Accounts"
        uri="/accounts"
        icon={<Icon path={mdiCashMultiple} size={1} />}
      />
      <NavLink
        label="Inbox"
        uri="/inbox"
        icon={<Icon path={mdiInbox} size={1} />}
        secondary={
          unmatched.count > 0 ? (
            <Chip label={unmatched.count} size="small" />
          ) : (
            <></>
          )
        }
      />
      <Divider />
      {accounts.list.isEmpty && (
        <Typography
          variant="caption"
          style={{
            paddingTop: "20px",
            display: "inline-block",
            textAlign: "center",
            width: "100%",
          }}
        >
          No account yet.
        </Typography>
      )}

      {accounts.list.list.map((a) => (
        <NavLink
          key={a.id}
          label={a.name}
          secondaryLabel={
            publicMode.enabled ? <></> : <AmountWidget amount={a.balance} />
          }
          uri={`/account/${a.id}`}
          icon={<AccountIconWidget account={a} />}
        />
      ))}
    </List>
  );
}

function NavLink(p: {
  icon: React.ReactElement;
  uri: string;
  label: string | React.ReactElement;
  secondaryLabel?: string | React.ReactElement;
  secondary?: React.ReactElement;
}): React.ReactElement {
  const location = useLocation();
  return (
    <RouterLink to={p.uri}>
      <ListItem secondaryAction={p.secondary} disablePadding>
        <ListItemButton selected={p.uri === location.pathname}>
          <ListItemIcon>{p.icon}</ListItemIcon>
          <ListItemText primary={p.label} secondary={p.secondaryLabel} />
        </ListItemButton>
      </ListItem>
    </RouterLink>
  );
}
