import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import { api } from "../../api/client";
import { Page } from "../../components/Page";
import { Table } from "../../components/Table";

const columns = [
  { key: "name", label: "Device" },
  { key: "owner", label: "Owner" },
  { key: "platform", label: "Platform" },
  { key: "ip", label: "VPN IP" },
  { key: "status", label: "Status" }
];

export function DevicesPage() {
  const queryClient = useQueryClient();
  const query = useQuery({
    queryKey: ["devices"],
    queryFn: api.devices
  });
  const profileQuery = useQuery({
    queryKey: ["device-profile", query.data?.[0]?.id ?? ""],
    queryFn: () => api.deviceProfile(query.data?.[0]?.id ?? ""),
    enabled: Boolean(query.data?.[0]?.id)
  });
  const revokeMutation = useMutation({
    mutationFn: api.revokeDevice,
    onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["devices"] })
  });
  const rotateMutation = useMutation({
    mutationFn: api.rotateDevice,
    onSuccess: () => void queryClient.invalidateQueries({ queryKey: ["devices"] })
  });

  const rows = query.data?.map((device) => ({
    id: device.id,
    name: device.name,
    owner: device.user_id ?? "assigned user",
    platform: device.platform,
    ip: device.assigned_ip ?? "-",
    status: device.status
  })) ?? [];

  return (
    <Page title="Devices" subtitle="Inspect enrolled clients, assignments, and profile lifecycle.">
      {query.isError ? <p className="notice">Unable to load devices from the API.</p> : null}
      <Table
        columns={columns}
        rows={rows}
        renderCell={(row, column) => <span>{row[column.key as keyof (typeof rows)[number]]}</span>}
      />
      {rows.length > 0 ? (
        <div className="grid two">
          <div className="card">
            <h4>Selected device profile</h4>
            <p className="notice">Admin view shows a debug template. The client private key stays on the device.</p>
            <pre className="code-block">{profileQuery.data?.profile.content ?? "Loading profile..."}</pre>
          </div>
          <div className="card">
            <h4>Device actions</h4>
            <p>Target: {rows[0].name}</p>
            <div className="action-row">
              <button className="button" onClick={() => rotateMutation.mutate(rows[0].id)}>Rotate profile</button>
              <button className="ghost-button" onClick={() => revokeMutation.mutate(rows[0].id)}>Revoke device</button>
            </div>
          </div>
        </div>
      ) : null}
    </Page>
  );
}
