import { useState, useEffect, useCallback } from 'react';
import { useClient } from 'hooks/useClient';
import { toast } from 'sonner';
import { Server, Radio, Plug, PlugZap, RefreshCw, Package, Loader2 } from 'lucide-react';
import type { SlskdApplication, SlskdServerState } from './shared';

// System panel — connection health and controls for the slskd daemon. GET /application carries the
// server block (state/address/username) and version info; PUT /server connects to Soulseek, DELETE
// /server disconnects. Basic version: a connection card with connect/disconnect, and a version card.

const POLL_MS = 3000;

export const SoulseekSystem = () => {
  const client = useClient();
  const [app, setApp] = useState<SlskdApplication | null>(null);
  const [busy, setBusy] = useState(false);

  const refresh = useCallback(async () => {
    try {
      setApp(await client.get<SlskdApplication>('/slskd/api/v0/application'));
    } catch {
      /* connection card will show the stale/empty state */
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() => {
    refresh();
    const timer = setInterval(refresh, POLL_MS);
    return () => clearInterval(timer);
  }, [refresh]);

  const server: SlskdServerState | undefined = app?.server;
  const connected = server?.isConnected ?? false;

  const connect = async () => {
    setBusy(true);
    try {
      await client.put('/slskd/api/v0/server');
      toast.success('Connecting to Soulseek…');
      await refresh();
    } catch (err) {
      toast.error(`Connect failed: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setBusy(false);
    }
  };

  const disconnect = async () => {
    setBusy(true);
    try {
      await client.delete('/slskd/api/v0/server');
      toast.success('Disconnected from Soulseek.');
      await refresh();
    } catch (err) {
      toast.error(`Disconnect failed: ${err instanceof Error ? err.message : String(err)}`);
    } finally {
      setBusy(false);
    }
  };

  const version = app?.version;

  return (
    <div className="h-full overflow-y-auto p-4">
      <div className="mx-auto flex max-w-2xl flex-col gap-4">
        <div className="flex items-center gap-2">
          <Server className="h-4 w-4 text-zinc-400" />
          <span className="text-sm font-medium text-zinc-100">System</span>
          <button
            type="button"
            onClick={refresh}
            title="Refresh"
            className="ml-auto rounded p-1 text-zinc-500 transition hover:bg-white/5 hover:text-zinc-200"
          >
            <RefreshCw className="h-3.5 w-3.5" />
          </button>
        </div>

        {/* Connection */}
        <div className="rounded-xl border border-white/10 bg-zinc-950">
          <div className="flex items-center gap-3 border-b border-white/10 px-4 py-3">
            <Radio className="h-4 w-4 shrink-0 text-zinc-400" />
            <span className={`inline-block h-2.5 w-2.5 shrink-0 rounded-full ${connected ? 'bg-green-500' : 'bg-red-500'}`} />
            <div className="min-w-0 flex-1">
              <div className="truncate text-sm font-medium text-zinc-100">{server?.state ?? 'Unknown'}</div>
              {server?.address && <div className="truncate text-xs text-zinc-500">{server.address}</div>}
            </div>
            {server?.username && <span className="shrink-0 text-xs text-zinc-400">{server.username}</span>}
          </div>
          <div className="flex items-center gap-2 p-3">
            <button
              type="button"
              onClick={connect}
              disabled={busy || connected}
              className="flex items-center gap-1.5 rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-sm text-zinc-200 transition hover:bg-white/10 disabled:opacity-40"
            >
              {busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <PlugZap className="h-3.5 w-3.5" />}
              Connect
            </button>
            <button
              type="button"
              onClick={disconnect}
              disabled={busy || !connected}
              className="flex items-center gap-1.5 rounded-lg border border-white/10 bg-white/5 px-3 py-1.5 text-sm text-zinc-200 transition hover:bg-white/10 disabled:opacity-40"
            >
              {busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Plug className="h-3.5 w-3.5" />}
              Disconnect
            </button>
          </div>
        </div>

        {/* Version */}
        <div className="rounded-xl border border-white/10 bg-zinc-950">
          <div className="flex items-center gap-2 border-b border-white/10 px-4 py-2.5">
            <Package className="h-4 w-4 text-zinc-400" />
            <span className="text-sm font-medium text-zinc-100">Version</span>
          </div>
          <div className="grid grid-cols-2 gap-2 p-3">
            <Field label="Current" value={version?.current ?? '—'} />
            <Field label="Latest" value={version?.latest ?? '—'} />
            <div className="col-span-2">
              {version?.isUpdateAvailable ? (
                <span className="inline-flex items-center gap-1.5 rounded-md bg-amber-500/10 px-2 py-1 text-xs text-amber-400">
                  <Package className="h-3.5 w-3.5" /> Update available
                </span>
              ) : (
                <span className="text-xs text-zinc-500">Up to date</span>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

type FieldProps = { label: string; value: string };

const Field = ({ label, value }: FieldProps) => (
  <div className="flex flex-col gap-1 rounded-lg border border-white/5 bg-white/[0.02] px-3 py-2">
    <span className="text-xs text-zinc-500">{label}</span>
    <span className="truncate text-sm font-medium tabular-nums text-zinc-100">{value}</span>
  </div>
);
