import LinkIcon from "@mui/icons-material/Link";
import RefreshIcon from "@mui/icons-material/Refresh";
import {
  IconButton,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tooltip,
  Typography,
} from "@mui/material";
import React from "react";
import { useNavigate } from "react-router-dom";
import { Device, DeviceApi, DeviceRelay, DeviceURL } from "../api/DeviceApi";
import { RelayApi, RelaysStatus } from "../api/RelayApi";
import { ServerApi } from "../api/ServerApi";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { BoolText } from "../widgets/BoolText";
import { CopyToClipboard } from "../widgets/CopyToClipboard";
import { RelayForcedState } from "../widgets/RelayForcedState";
import { SolarEnergyRouteContainer } from "../widgets/SolarEnergyRouteContainer";
import { TimeWidget } from "../widgets/TimeWidget";

export function RelaysListRoute(p: {
  homeWidget?: boolean;
}): React.ReactElement {
  const loadKey = React.useRef(1);

  const [list, setList] = React.useState<DeviceRelay[] | undefined>();
  const [devices, setDevices] = React.useState<Device[] | undefined>();
  const [status, setStatus] = React.useState<RelaysStatus | undefined>();

  const load = async () => {
    setList(await RelayApi.GetList());
    setDevices(await DeviceApi.ValidatedList());
    setStatus(await RelayApi.GetRelaysStatus());

    list?.sort((a, b) => b.priority - a.priority);
  };

  const reload = () => {
    loadKey.current += 1;
    setList(undefined);
  };

  return (
    <>
      <SolarEnergyRouteContainer
        label="Relays list"
        homeWidget={p.homeWidget}
        actions={
          <Tooltip title="Refresh list">
            <IconButton onClick={reload}>
              <RefreshIcon />
            </IconButton>
          </Tooltip>
        }
      >
        <AsyncWidget
          loadKey={loadKey.current}
          ready={!!list}
          errMsg="Failed to load the list of relays!"
          load={load}
          build={() => (
            <RelaysList
              onReload={reload}
              list={list!}
              devices={devices!}
              status={status!}
            />
          )}
        />
      </SolarEnergyRouteContainer>
    </>
  );
}

function RelaysList(p: {
  list: DeviceRelay[];
  devices: Device[];
  status: RelaysStatus;
  onReload: () => void;
}): React.ReactElement {
  const navigate = useNavigate();

  const openDevicePage = (relay: DeviceRelay) => {
    const dev = p.devices.find((d) => d.relays.find((r) => r.id === relay.id));
    navigate(DeviceURL(dev!));
  };

  if (p.list.length === 0) {
    return <Typography>There is no configured relay yet!</Typography>;
  }

  return (
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 650 }}>
        <TableHead>
          <TableRow>
            <TableCell>Name</TableCell>
            <TableCell>Enabled</TableCell>
            <TableCell>Priority</TableCell>
            <TableCell>Consumption</TableCell>
            <TableCell>Status</TableCell>
            <TableCell>Forced state</TableCell>
            <TableCell></TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {p.list.map((row) => (
            <TableRow
              key={row.name}
              sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
              hover
              onDoubleClick={() => openDevicePage(row)}
            >
              <TableCell>{row.name}</TableCell>
              <TableCell>
                <BoolText val={row.enabled} positive="YES" negative="NO" />
              </TableCell>
              <TableCell>{row.priority}</TableCell>
              <TableCell>{row.consumption}</TableCell>
              <TableCell>
                <BoolText
                  val={p.status.get(row.id)!.on}
                  positive="ON"
                  negative="OFF"
                />{" "}
                for <TimeWidget diff time={p.status.get(row.id)!.for} />
              </TableCell>
              <TableCell>
                <RelayForcedState
                  relay={row}
                  state={p.status.get(row.id)!}
                  onUpdated={p.onReload}
                />
              </TableCell>
              <TableCell>
                <Tooltip title="Copy legacy api status">
                  <CopyToClipboard
                    content={
                      ServerApi.Config.unsecure_origin +
                      `/relay/${row.id}/legacy_state`
                    }
                  >
                    <IconButton>
                      <LinkIcon />
                    </IconButton>
                  </CopyToClipboard>
                </Tooltip>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}
