import { FormEvent, useEffect, useState } from "react";
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: "Gateway" },
  { key: "endpoint", label: "Endpoint" },
  { key: "cidr", label: "VPN CIDR" },
  { key: "status", label: "Status" }
];

export function GatewaysPage() {
  const queryClient = useQueryClient();
  const query = useQuery({
    queryKey: ["gateways"],
    queryFn: api.gateways
  });
  const syncQuery = useQuery({
    queryKey: ["gateway-sync", query.data?.[0]?.id ?? ""],
    queryFn: () => api.gatewaySync(query.data?.[0]?.id ?? ""),
    enabled: Boolean(query.data?.[0]?.id)
  });
  const [form, setForm] = useState({
    endpoint: "",
    public_key: "",
    listen_port: 51820,
    vpn_cidr: "100.96.0.0/24",
    dns_servers: "10.20.0.53",
    is_active: true
  });
  const updateMutation = useMutation({
    mutationFn: (payload: Parameters<typeof api.updateGateway>[1]) => api.updateGateway(query.data?.[0]?.id ?? "", payload),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: ["gateways"] });
      void queryClient.invalidateQueries({ queryKey: ["gateway-sync"] });
    }
  });

  const rows = query.data?.map((gateway) => ({
    name: gateway.name,
    endpoint: gateway.endpoint,
    cidr: gateway.vpn_cidr,
    status: gateway.is_active ? "active" : "inactive"
  })) ?? [];

  useEffect(() => {
    if (query.data?.[0]) {
      const gateway = query.data[0];
      setForm({
        endpoint: gateway.endpoint,
        public_key: gateway.public_key,
        listen_port: gateway.listen_port,
        vpn_cidr: gateway.vpn_cidr,
        dns_servers: gateway.dns_servers.join(", "),
        is_active: gateway.is_active
      });
    }
  }, [query.data]);

  function onSubmit(event: FormEvent) {
    event.preventDefault();
    updateMutation.mutate({
      endpoint: form.endpoint,
      public_key: form.public_key,
      listen_port: Number(form.listen_port),
      vpn_cidr: form.vpn_cidr,
      dns_servers: form.dns_servers.split(",").map((value) => value.trim()).filter(Boolean),
      is_active: form.is_active
    });
  }

  return (
    <Page title="Gateways" subtitle="Track WireGuard endpoints and sync state.">
      {query.isError ? <p className="notice">Unable to load gateways from the API.</p> : null}
      <Table
        columns={columns}
        rows={rows}
        renderCell={(row, column) => <span>{row[column.key as keyof (typeof rows)[number]]}</span>}
      />
      <form className="inline-form" onSubmit={onSubmit}>
        <input placeholder="endpoint" value={form.endpoint} onChange={(event) => setForm((value) => ({ ...value, endpoint: event.target.value }))} />
        <input placeholder="public key" value={form.public_key} onChange={(event) => setForm((value) => ({ ...value, public_key: event.target.value }))} />
        <input placeholder="listen port" type="number" value={form.listen_port} onChange={(event) => setForm((value) => ({ ...value, listen_port: Number(event.target.value) }))} />
        <input placeholder="vpn cidr" value={form.vpn_cidr} onChange={(event) => setForm((value) => ({ ...value, vpn_cidr: event.target.value }))} />
        <input placeholder="dns servers" value={form.dns_servers} onChange={(event) => setForm((value) => ({ ...value, dns_servers: event.target.value }))} />
        <label className="checkbox">
          <input type="checkbox" checked={form.is_active} onChange={(event) => setForm((value) => ({ ...value, is_active: event.target.checked }))} />
          Active
        </label>
        <button className="button" type="submit" disabled={updateMutation.isPending}>Update gateway</button>
      </form>
      {syncQuery.data ? (
        <div className="card">
          <h4>Sync bundle preview</h4>
          <pre className="code-block">{JSON.stringify(syncQuery.data, null, 2)}</pre>
        </div>
      ) : null}
    </Page>
  );
}
