import { ApiError } from "../../api/client";
import type { Machine } from "../../api/types";
import { Badge } from "../../components/ui/Badge";
import { Drawer } from "../../components/ui/Drawer";
import { Spinner } from "../../components/ui/Spinner";
import { EmptyState, ErrorState } from "../../components/ui/States";
import { machineTone } from "../../components/ui/status";
import { StatusDot } from "../../components/ui/StatusDot";
import { absoluteTime, formatDuration, relativeTime } from "../../lib/time";
import { useMachineHistory } from "./hooks";

interface MachineDetailDrawerProps {
  machine: Machine | null;
  onClose: () => void;
}

function Row({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <>
      <div className="mdetail__k">{label}</div>
      <div className="mdetail__v">{children}</div>
    </>
  );
}

/**
 * Read and inspect surface for a single machine: facts plus session and event
 * history. A side drawer (not a modal): inspecting a machine is a lightweight,
 * non-blocking read, and the list stays visible behind it for context.
 */
export function MachineDetailDrawer({ machine, onClose }: MachineDetailDrawerProps) {
  const history = useMachineHistory(machine?.agent_id ?? null);

  return (
    <Drawer
      open={machine != null}
      ariaLabel={`Machine detail: ${machine?.hostname ?? ""}`}
      title={
        <>
          {machine && (
            <StatusDot tone={machineTone(machine.status)} label={machine.status} />
          )}
          <span className="mono">{machine?.hostname}</span>
        </>
      }
      subtitle={machine ? `Agent ${machine.agent_id}` : undefined}
      onClose={onClose}
    >
      {machine && (
        <div className="mdetail__grid">
          <Row label="Status">
            <Badge tone={machineTone(machine.status)} dot>
              {machine.status}
            </Badge>
          </Row>
          <Row label="OS version">{machine.os_version ?? "Unknown"}</Row>
          <Row label="Connection">
            {machine.is_persistent ? (
              <Badge tone="accent">Persistent</Badge>
            ) : (
              <Badge tone="neutral">Attended</Badge>
            )}{" "}
            {machine.is_elevated && <Badge tone="ok">Elevated</Badge>}
          </Row>
          <Row label="First seen">
            <span className="mono" title={absoluteTime(machine.first_seen)}>
              {relativeTime(machine.first_seen)}
            </span>
          </Row>
          <Row label="Last seen">
            <span className="mono" title={absoluteTime(machine.last_seen)}>
              {relativeTime(machine.last_seen)}
            </span>
          </Row>
        </div>
      )}

      <div className="mdetail__section">
        <h3>Session history</h3>
        {history.isLoading ? (
          <Spinner label="Loading history" />
        ) : history.isError ? (
          <ErrorState
            title="Could not load history"
            message={
              history.error instanceof ApiError
                ? history.error.message
                : "The server did not respond. Try reopening this panel."
            }
          />
        ) : !history.data || history.data.sessions.length === 0 ? (
          <EmptyState
            title="No sessions yet"
            message="Support and managed sessions for this machine will be listed here."
          />
        ) : (
          <table className="minitable">
            <thead>
              <tr>
                <th>Started</th>
                <th>Duration</th>
                <th>Type</th>
                <th>Code</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {history.data.sessions.map((s) => (
                <tr key={s.id}>
                  <td className="mono" title={absoluteTime(s.started_at)}>
                    {relativeTime(s.started_at)}
                  </td>
                  <td className="mono">{formatDuration(s.duration_secs)}</td>
                  <td>{s.is_support_session ? "Support" : "Managed"}</td>
                  <td className="mono">{s.support_code ?? "None"}</td>
                  <td>{s.status}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {history.data && history.data.events.length > 0 && (
        <div className="mdetail__section">
          <h3>Recent events</h3>
          <table className="minitable">
            <thead>
              <tr>
                <th>Time</th>
                <th>Event</th>
                <th>Viewer</th>
                <th>IP</th>
              </tr>
            </thead>
            <tbody>
              {history.data.events.slice(0, 25).map((e) => (
                <tr key={e.id}>
                  <td className="mono" title={absoluteTime(e.timestamp)}>
                    {relativeTime(e.timestamp)}
                  </td>
                  <td>{e.event_type}</td>
                  <td>{e.viewer_name ?? "None"}</td>
                  <td className="mono">{e.ip_address ?? "None"}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </Drawer>
  );
}
