import EditIcon from "@mui/icons-material/Edit";
import {
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableRow,
  Tooltip,
} from "@mui/material";
import React from "react";
import { Device } from "../../api/DeviceApi";
import { EditDeviceMetadataDialog } from "../../dialogs/EditDeviceMetadataDialog";
import { formatDate } from "../../widgets/TimeWidget";
import { DeviceRouteCard } from "./DeviceRouteCard";

export function GeneralDeviceInfo(p: {
  device: Device;
  onReload: () => void;
}): React.ReactElement {
  const [dialogOpen, setDialogOpen] = React.useState(false);

  return (
    <>
      {dialogOpen && (
        <EditDeviceMetadataDialog
          device={p.device}
          onClose={() => setDialogOpen(false)}
          onUpdated={p.onReload}
        />
      )}
      <DeviceRouteCard
        title="General device information"
        actions={
          <Tooltip title="Edit device information">
            <IconButton onClick={() => setDialogOpen(true)}>
              <EditIcon />
            </IconButton>
          </Tooltip>
        }
      >
        <Table size="small">
          <TableBody>
            <DeviceInfoProperty label="ID" value={p.device.id} />
            <DeviceInfoProperty
              label="Reference"
              value={p.device.info.reference}
            />
            <DeviceInfoProperty label="Version" value={p.device.info.version} />
            <DeviceInfoProperty label="Name" value={p.device.name} />
            <DeviceInfoProperty
              label="Description"
              value={p.device.description}
            />
            <DeviceInfoProperty
              label="Created"
              value={formatDate(p.device.time_create)}
            />
            <DeviceInfoProperty
              label="Updated"
              value={formatDate(p.device.time_update)}
            />
            <DeviceInfoProperty
              label="Enabled"
              value={p.device.enabled ? "YES" : "NO"}
              color={p.device.enabled ? "green" : "red"}
            />
            <DeviceInfoProperty
              label="Maximum number of relays"
              value={p.device.info.max_relays.toString()}
            />
            <DeviceInfoProperty
              label="Number of configured relays"
              value={p.device.relays.length.toString()}
            />
          </TableBody>
        </Table>
      </DeviceRouteCard>
    </>
  );
}

function DeviceInfoProperty(p: {
  icon?: React.ReactElement;
  label: string;
  value: string;
  color?: string;
}): React.ReactElement {
  return (
    <TableRow hover sx={{ "&:last-child td, &:last-child th": { border: 0 } }}>
      <TableCell>{p.label}</TableCell>
      <TableCell style={{ color: p.color }}>{p.value}</TableCell>
    </TableRow>
  );
}
