import { Fragment, useCallback, useState } from 'react';
import { api, type Device } from '../api';
import { usePolling } from '../hooks/usePolling';

interface Props {
  org?: string;
}

function statusDot(lastSeen: string): string {
  const ago = Date.now() - new Date(lastSeen).getTime();
  if (ago < 10 * 60_000) return 'bg-green-500';
  if (ago < 30 * 60_000) return 'bg-yellow-500';
  return 'bg-red-500';
}

function relativeTime(iso: string | null): string {
  if (!iso) return 'never';
  const ago = Date.now() - new Date(iso).getTime();
  if (ago < 60_000) return 'just now';
  if (ago < 3600_000) return `${Math.floor(ago / 60_000)}m ago`;
  if (ago < 86400_000) return `${Math.floor(ago / 3600_000)}h ago`;
  return `${Math.floor(ago / 86400_000)}d ago`;
}

function truncId(id: string, len = 8): string {
  return id.length > len ? id.slice(0, len) + '…' : id;
}

function formatError(err: unknown): string {
  if (typeof err === 'string') return err;
  if (typeof err === 'object' && err !== null) {
    const e = err as Record<string, unknown>;
    let msg = String(e.error ?? JSON.stringify(err));
    if (e.count && Number(e.count) > 1) msg += ` (x${e.count})`;
    return msg;
  }
  return String(err);
}

export function DeviceStatus({ org }: Props) {
  const [expandedDevice, setExpandedDevice] = useState<string | null>(null);
  const fetcher = useCallback(() => api.devices({ org }), [org]);
  const { data, error, loading } = usePolling<Device[]>(fetcher, 30000);

  if (!loading && !error && data?.length === 0) return null;

  return (
    <div className="bg-surface-raised border border-border rounded-lg overflow-hidden">
      <div className="px-4 py-3 border-b border-border flex items-center justify-between">
        <h2 className="text-sm font-semibold text-text-primary">Connected Devices</h2>
        <span className="text-xs text-text-muted flex items-center gap-3">
          <span className="inline-flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-green-500" /> &lt;10m</span>
          <span className="inline-flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-yellow-500" /> &lt;30m</span>
          <span className="inline-flex items-center gap-1"><span className="w-2 h-2 rounded-full bg-red-500" /> &gt;30m</span>
          <span className="ml-2">{loading ? 'loading...' : error ? 'error' : `${data?.length ?? 0} device${data?.length !== 1 ? 's' : ''}`}</span>
        </span>
      </div>
      <div className="overflow-auto max-h-[400px]">
        <table className="w-full text-xs">
          <thead>
            <tr className="border-b border-border text-text-muted text-left">
              <th className="px-4 py-2 font-medium">Device</th>
              <th className="px-4 py-2 font-medium">Org</th>
              <th className="px-4 py-2 font-medium">Status</th>
              <th className="px-4 py-2 font-medium">Last Pushed</th>
              <th className="px-4 py-2 font-medium">Version</th>
              <th className="px-4 py-2 font-medium">Daemon Status</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border-subtle">
            {data?.map((d) => (
              <Fragment key={d.device_id}>
              <tr className="hover:bg-surface-overlay transition-colors">
                <td className="px-4 py-2 text-text-primary" title={d.device_id}>
                  {d.device_name || truncId(d.device_id)}
                </td>
                <td className="px-4 py-2 text-text-secondary font-mono">
                  {d.org || '—'}
                </td>
                <td className="px-4 py-2">
                  <span className="inline-flex items-center gap-1.5">
                    <span className={`w-2 h-2 rounded-full ${statusDot(d.last_seen_at)}`} />
                    <span className="text-text-secondary">{relativeTime(d.last_seen_at)}</span>
                  </span>
                </td>
                <td className="px-4 py-2 text-text-secondary">
                  {relativeTime(d.last_push_at)}
                </td>
                <td className="px-4 py-2 text-text-muted font-mono">
                  {d.daemon_version || '—'}
                </td>
                <td className="px-4 py-2">
                  <span className="text-text-secondary">{d.status}</span>
                  {d.queue_size > 0 && (
                    <span className="ml-2 text-text-muted">q:{d.queue_size}</span>
                  )}
                  {d.recent_errors.length > 0 && !(
                    (Date.now() - new Date(d.last_seen_at).getTime()) < 10 * 60_000 &&
                    (d.status === 'idle' || d.status === 'pushing')
                  ) && (
                    <button
                      onClick={() => setExpandedDevice(expandedDevice === d.device_id ? null : d.device_id)}
                      className="ml-2 text-red-400 hover:text-red-300 underline decoration-dotted cursor-pointer"
                    >
                      {d.recent_errors.length} err
                    </button>
                  )}
                </td>
              </tr>
              {expandedDevice === d.device_id && d.recent_errors.length > 0 && (
                <tr>
                  <td colSpan={6} className="px-4 py-2 bg-surface-overlay">
                    <div className="space-y-1 max-h-40 overflow-y-auto">
                      {d.recent_errors.map((err, i) => (
                        <p key={i} className="text-xs text-red-400 font-mono whitespace-pre-wrap break-all">
                          {formatError(err)}
                        </p>
                      ))}
                    </div>
                  </td>
                </tr>
              )}
              </Fragment>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
