'use client';

import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { RefreshCw, Plus, Trash2, Pencil, Server, CheckCircle, AlertCircle, WrenchIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';

interface PoolServer {
  id: string;
  name: string;
  host: string;
  sshPort: number;
  sshUser: string;
  maxInstances: number;
  currentInstances: number;
  status: 'active' | 'maintenance' | 'offline';
  region?: string;
  notes?: string;
  hasKey: boolean;
  available: boolean;
  freeSlots: number;
  createdAt: string;
}

const API = '/api/proxy/api/v1/inventory/pool-servers';

async function fetchServers(): Promise<PoolServer[]> {
  const res = await fetch(API);
  if (!res.ok) throw new Error('Failed to load pool servers');
  return res.json();
}

async function createServer(data: Record<string, unknown>): Promise<PoolServer> {
  const res = await fetch(API, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.message ?? 'Failed to create server');
  }
  return res.json();
}

async function updateServer(id: string, data: Record<string, unknown>): Promise<PoolServer> {
  const res = await fetch(`${API}/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.message ?? 'Failed to update server');
  }
  return res.json();
}

async function deleteServer(id: string): Promise<void> {
  const res = await fetch(`${API}/${id}`, { method: 'DELETE' });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.message ?? 'Failed to delete server');
  }
}

const STATUS_ICONS = {
  active: <CheckCircle className="w-4 h-4 text-green-500" />,
  maintenance: <WrenchIcon className="w-4 h-4 text-yellow-500" />,
  offline: <AlertCircle className="w-4 h-4 text-red-500" />,
};

const STATUS_LABELS = { active: '运行中', maintenance: '维护中', offline: '离线' };

// ── Add/Edit Modal ──────────────────────────────────────────────────────────

function ServerModal({
  server,
  onClose,
  onSave,
}: {
  server?: PoolServer;
  onClose: () => void;
  onSave: (data: Record<string, unknown>) => Promise<void>;
}) {
  const [saving, setSaving] = useState(false);
  const [form, setForm] = useState({
    name: server?.name ?? '',
    host: server?.host ?? '',
    sshPort: server?.sshPort ?? 22,
    sshUser: server?.sshUser ?? '',
    sshKey: '',
    maxInstances: server?.maxInstances ?? 10,
    status: server?.status ?? 'active',
    region: server?.region ?? '',
    notes: server?.notes ?? '',
  });

  const set = (field: string) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) =>
    setForm((prev) => ({ ...prev, [field]: e.target.value }));

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const payload: Record<string, unknown> = { ...form };
      if (!form.sshKey) delete payload.sshKey; // Don't send empty key on edit
      await onSave(payload);
      onClose();
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '保存失败');
    } finally {
      setSaving(false);
    }
  };

  const inputClass = 'w-full rounded-md border bg-background px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary';
  const labelClass = 'block text-xs text-muted-foreground mb-1';

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
      <div className="bg-card rounded-xl border shadow-2xl w-full max-w-lg max-h-[90vh] overflow-y-auto">
        <div className="flex items-center justify-between px-6 py-4 border-b">
          <h2 className="text-base font-semibold">{server ? '编辑服务器' : '添加服务器'}</h2>
          <button onClick={onClose} className="text-muted-foreground hover:text-foreground text-xl leading-none">×</button>
        </div>
        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className={labelClass}>名称 *</label>
              <input required value={form.name} onChange={set('name')} placeholder="训练服务器" className={inputClass} />
            </div>
            <div>
              <label className={labelClass}>地区</label>
              <input value={form.region} onChange={set('region')} placeholder="深圳" className={inputClass} />
            </div>
          </div>
          <div className="grid grid-cols-3 gap-4">
            <div className="col-span-2">
              <label className={labelClass}>主机 IP / 域名 *</label>
              <input required value={form.host} onChange={set('host')} placeholder="89.185.24.182" className={inputClass} />
            </div>
            <div>
              <label className={labelClass}>SSH 端口</label>
              <input type="number" value={form.sshPort} onChange={set('sshPort')} className={inputClass} />
            </div>
          </div>
          <div>
            <label className={labelClass}>SSH 用户名 *</label>
            <input required value={form.sshUser} onChange={set('sshUser')} placeholder="ceshi" className={inputClass} />
          </div>
          <div>
            <label className={labelClass}>SSH 私钥 {server ? '（留空保留原有密钥）' : '*'}</label>
            <textarea
              required={!server}
              value={form.sshKey}
              onChange={set('sshKey')}
              rows={5}
              placeholder="-----BEGIN OPENSSH PRIVATE KEY-----&#10;..."
              className={`${inputClass} font-mono text-xs resize-none`}
            />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className={labelClass}>最大实例数</label>
              <input type="number" min={1} max={500} value={form.maxInstances} onChange={set('maxInstances')} className={inputClass} />
            </div>
            <div>
              <label className={labelClass}>状态</label>
              <select value={form.status} onChange={set('status')} className={inputClass}>
                <option value="active">运行中</option>
                <option value="maintenance">维护中</option>
                <option value="offline">离线</option>
              </select>
            </div>
          </div>
          <div>
            <label className={labelClass}>备注</label>
            <textarea value={form.notes} onChange={set('notes')} rows={2} className={`${inputClass} resize-none`} />
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <button type="button" onClick={onClose} className="px-4 py-2 rounded-md text-sm bg-accent text-foreground hover:bg-accent/80">取消</button>
            <button type="submit" disabled={saving} className="px-4 py-2 rounded-md text-sm bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50">
              {saving ? '保存中...' : '保存'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ── Page ────────────────────────────────────────────────────────────────────

export default function ServerPoolPage() {
  const { t } = useTranslation('sidebar');
  const queryClient = useQueryClient();
  const [showModal, setShowModal] = useState(false);
  const [editingServer, setEditingServer] = useState<PoolServer | undefined>();

  const { data: servers = [], isLoading, error, refetch } = useQuery<PoolServer[]>({
    queryKey: ['pool-servers'],
    queryFn: fetchServers,
  });

  const handleSave = async (data: Record<string, unknown>) => {
    if (editingServer) {
      await updateServer(editingServer.id, data);
      toast.success('服务器已更新');
    } else {
      await createServer(data);
      toast.success('服务器已添加');
    }
    queryClient.invalidateQueries({ queryKey: ['pool-servers'] });
  };

  const handleDelete = async (server: PoolServer) => {
    if (!confirm(`确定要删除服务器「${server.name}」吗？\n当前有 ${server.currentInstances} 个活跃实例时无法删除。`)) return;
    try {
      await deleteServer(server.id);
      toast.success('服务器已删除');
      queryClient.invalidateQueries({ queryKey: ['pool-servers'] });
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '删除失败');
    }
  };

  const totalCapacity = servers.reduce((a, s) => a + s.maxInstances, 0);
  const totalUsed = servers.reduce((a, s) => a + s.currentInstances, 0);

  return (
    <div className="space-y-5">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-semibold text-foreground">服务器池管理</h1>
          <p className="text-sm text-muted-foreground mt-0.5">
            管理用于部署{t('openclawInstances')}的物理/云服务器资源池
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button onClick={() => refetch()} disabled={isLoading} className="flex items-center gap-1.5 px-3 py-2 rounded-md text-sm bg-accent text-foreground hover:bg-accent/80 disabled:opacity-50">
            <RefreshCw className={`w-4 h-4 ${isLoading ? 'animate-spin' : ''}`} /> 刷新
          </button>
          <button onClick={() => { setEditingServer(undefined); setShowModal(true); }} className="flex items-center gap-1.5 px-3 py-2 rounded-md text-sm bg-primary text-primary-foreground hover:bg-primary/90">
            <Plus className="w-4 h-4" /> 添加服务器
          </button>
        </div>
      </div>

      {/* Summary stats */}
      {servers.length > 0 && (
        <div className="grid grid-cols-3 gap-4">
          {[
            { label: '服务器总数', value: servers.length },
            { label: '总容量（实例）', value: totalCapacity },
            { label: '已用 / 空闲', value: `${totalUsed} / ${totalCapacity - totalUsed}` },
          ].map(({ label, value }) => (
            <div key={label} className="bg-card rounded-lg border p-4">
              <p className="text-xs text-muted-foreground">{label}</p>
              <p className="text-2xl font-semibold mt-1">{value}</p>
            </div>
          ))}
        </div>
      )}

      {/* Error */}
      {error && (
        <div className="rounded-lg bg-destructive/10 border border-destructive/30 p-4 text-red-400 text-sm">
          加载失败：{error instanceof Error ? error.message : String(error)}
        </div>
      )}

      {/* Loading */}
      {isLoading && (
        <div className="space-y-3">
          {[1, 2].map((i) => (
            <div key={i} className="bg-card rounded-lg border p-5 animate-pulse h-24" />
          ))}
        </div>
      )}

      {/* Server list */}
      {!isLoading && !error && (
        <div className="space-y-3">
          {servers.length === 0 ? (
            <div className="bg-card rounded-lg border p-12 text-center">
              <Server className="w-10 h-10 text-muted-foreground mx-auto mb-3" />
              <p className="text-muted-foreground text-sm mb-4">暂无服务器，添加第一台开始部署{t('openclawInstances')}</p>
              <button onClick={() => setShowModal(true)} className="px-4 py-2 rounded-md text-sm bg-primary text-primary-foreground hover:bg-primary/90">
                添加服务器
              </button>
            </div>
          ) : (
            servers.map((server) => (
              <div key={server.id} className="bg-card rounded-lg border p-5">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-3">
                    {STATUS_ICONS[server.status]}
                    <div>
                      <div className="flex items-center gap-2">
                        <span className="font-medium text-sm">{server.name}</span>
                        {server.region && (
                          <span className="px-1.5 py-0.5 rounded text-xs bg-accent text-muted-foreground">{server.region}</span>
                        )}
                        <span className="text-xs text-muted-foreground">{STATUS_LABELS[server.status]}</span>
                      </div>
                      <p className="text-xs text-muted-foreground mt-0.5">
                        {server.sshUser}@{server.host}:{server.sshPort}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <button onClick={() => { setEditingServer(server); setShowModal(true); }} className="p-1.5 rounded hover:bg-accent text-muted-foreground hover:text-foreground">
                      <Pencil className="w-3.5 h-3.5" />
                    </button>
                    <button onClick={() => handleDelete(server)} className="p-1.5 rounded hover:bg-destructive/10 text-muted-foreground hover:text-red-400">
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                </div>

                {/* Capacity bar */}
                <div className="mt-4">
                  <div className="flex items-center justify-between text-xs text-muted-foreground mb-1">
                    <span>实例用量</span>
                    <span>{server.currentInstances} / {server.maxInstances}（剩余 {server.freeSlots} 个）</span>
                  </div>
                  <div className="h-1.5 rounded-full bg-accent overflow-hidden">
                    <div
                      className={`h-full rounded-full transition-all ${
                        server.currentInstances / server.maxInstances > 0.8 ? 'bg-red-500' :
                        server.currentInstances / server.maxInstances > 0.5 ? 'bg-yellow-500' : 'bg-green-500'
                      }`}
                      style={{ width: `${Math.min(100, (server.currentInstances / server.maxInstances) * 100)}%` }}
                    />
                  </div>
                </div>

                {server.notes && (
                  <p className="text-xs text-muted-foreground mt-3 border-t pt-2">{server.notes}</p>
                )}
              </div>
            ))
          )}
        </div>
      )}

      {showModal && (
        <ServerModal
          server={editingServer}
          onClose={() => { setShowModal(false); setEditingServer(undefined); }}
          onSave={handleSave}
        />
      )}
    </div>
  );
}
