import CallMadeIcon from "@mui/icons-material/CallMade";
import CallReceivedIcon from "@mui/icons-material/CallReceived";
import React from "react";
import { Movement, MovementApi } from "../api/MovementsApi";
import { useAccounts } from "../hooks/AccountsListProvider";
import { fmtDateFromTime } from "../utils/DateUtils";
import { AccountIconWidget } from "./AccountIconWidget";
import { AmountWidget } from "./AmountWidget";
import { AsyncWidget } from "./AsyncWidget";

export function AsyncMovementWidget(p: { id: number }): React.ReactElement {
  const [movement, setMovement] = React.useState<Movement | undefined>();

  const load = async () => {
    setMovement(await MovementApi.GetSingleMovement(p.id));
  };

  return (
    <AsyncWidget
      loadKey={p.id}
      load={load}
      errMsg="Failed to load movement!"
      build={() => <MovementWidget movement={movement!} />}
    />
  );
}

export function MovementWidget(p: { movement: Movement }): React.ReactElement {
  const accounts = useAccounts();

  return (
    <span
      style={{
        display: "inline-flex",
        alignItems: "center",
        height: "100%",
      }}
    >
      {p.movement.amount > 0 ? (
        <CallReceivedIcon color="success" />
      ) : (
        <CallMadeIcon color="error" />
      )}
      <span
        style={{
          marginLeft: "5px",
          display: "inline-flex",
          flexDirection: "column",
          justifyContent: "center",
          height: "100%",
        }}
      >
        <span style={{ height: "1em", lineHeight: 1 }}>
          {p.movement.label}
        </span>
        <span style={{ display: "flex", alignItems: "center", lineHeight: 1 }}>
          <AmountWidget amount={p.movement.amount} />
          <span style={{ width: "0.5em" }} />
          &bull;
          <span style={{ width: "0.5em" }} />
          <AccountIconWidget account={accounts.get(p.movement.account_id)!} />
          {accounts.get(p.movement.account_id)?.name}
          <span style={{ width: "0.5em" }} />
          &bull; <span style={{ width: "0.5em" }} />
          {fmtDateFromTime(p.movement.time)}
        </span>
      </span>
    </span>
  );
}
