import React, { useEffect, useState, useCallback } from "react";
import { api } from "../api.js";
import InstanceCard from "../components/InstanceCard.jsx";

const PRESETS = [
  { key: "small", label: "S", cpu: 1, ram: 1024, disk: 10 },
  { key: "medium", label: "M", cpu: 2, ram: 2048, disk: 20 },
  { key: "large", label: "L", cpu: 4, ram: 8192, disk: 50 },
  { key: "xlarge", label: "XL", cpu: 8, ram: 16384, disk: 100 },
];

function matchPreset(templates, preset) {
  return templates.find(
    (template) =>
      template.cores === preset.cpu &&
      template.memory_mb === preset.ram &&
      template.disk_gb === preset.disk,
  ) || templates
    .filter(
      (template) =>
        template.cores >= preset.cpu &&
        template.memory_mb >= preset.ram &&
        template.disk_gb >= preset.disk,
    )
    .sort((a, b) => a.cores + a.memory_mb / 1024 + a.disk_gb - (b.cores + b.memory_mb / 1024 + b.disk_gb))[0] || null;
}

function StatCard({ label, value, tone = "default" }) {
  return (
    <div className={`stat-card stat-${tone}`}>
      <div className="stat-card-body">
        <div className="stat-card-label">{label}</div>
        <div className="stat-card-value">{value}</div>
      </div>
    </div>
  );
}

export default function Dashboard() {
  const [instances, setInstances] = useState([]);
  const [templates, setTemplates] = useState([]);
  const [activeTab, setActiveTab] = useState("vm");
  const [showForm, setShowForm] = useState(false);
  const [name, setName] = useState("");
  const [ciuser, setCiuser] = useState("root");
  const [cipassword, setCipassword] = useState("");
  const [templateId, setTemplateId] = useState("");
  const [selectedPreset, setSelectedPreset] = useState(null);
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    const [instanceList, templateList] = await Promise.all([
      api.listInstances(),
      api.listTemplates(),
    ]);
    setInstances(instanceList);
    setTemplates(templateList);
  }, []);

  useEffect(() => {
    refresh().finally(() => setLoading(false));
    const timer = setInterval(refresh, 8000);
    return () => clearInterval(timer);
  }, [refresh]);

  const typeTemplates = templates.filter((template) => template.guest_type === activeTab);
  const visibleInstances = instances.filter((instance) => instance.guest_type === activeTab);

  useEffect(() => {
    if (selectedPreset && activeTab === "vm") {
      const preset = PRESETS.find((item) => item.key === selectedPreset);
      const match = preset ? matchPreset(typeTemplates, preset) : null;
      setTemplateId(match ? String(match.id) : "");
    } else {
      setTemplateId(typeTemplates.length ? String(typeTemplates[0].id) : "");
    }
  }, [activeTab, templates, selectedPreset]);

  function switchTab(tab) {
    setActiveTab(tab);
    setSelectedPreset(null);
    setError("");
  }

  async function onCreate(event) {
    event.preventDefault();
    if (busy || !templateId || !name.trim()) return;

    setError("");
    setBusy(true);
    try {
      await api.createInstance({
        name: name.trim(),
        template_id: Number(templateId),
        // Для архивного LXC backend создаёт новый пароль root.
        ciuser: activeTab === "vm" ? ciuser : "root",
        cipassword: cipassword || "",
      });
      setName("");
      setCipassword("");
      setShowForm(false);
      await refresh();
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  }

  async function onAction(id, action) {
    try {
      await api.instanceAction(id, action);
      await refresh();
    } catch (err) {
      setError(err.message);
    }
  }

  async function onDelete(id) {
    if (!confirm("Удалить инстанс?")) return;
    try {
      await api.deleteInstance(id);
      await refresh();
    } catch (err) {
      setError(err.message);
    }
  }

  const stats = {
    total: instances.length,
    running: instances.filter((item) => item.status === "running").length,
    stopped: instances.filter((item) => item.status === "stopped").length,
    error: instances.filter((item) => item.status === "error").length,
  };

  return (
    <div className="container">
      <div className="dashboard-header">
        <div>
          <h1 className="page-title">Мои VPS</h1>
          <p className="page-sub">
            {stats.total === 0 ? "Нет активных серверов" : `${stats.running} из ${stats.total} запущено`}
          </p>
        </div>
        <button className={showForm ? "btn" : "btn btn-primary"} onClick={() => setShowForm((value) => !value)}>
          {showForm ? "✕ Отмена" : "+ Новый VPS"}
        </button>
      </div>

      {stats.total > 0 && (
        <div className="stats-grid">
          <StatCard label="Всего" value={stats.total} />
          <StatCard label="Запущено" value={stats.running} tone="success" />
          <StatCard label="Остановлено" value={stats.stopped} tone="muted" />
          {stats.error > 0 && <StatCard label="Ошибки" value={stats.error} tone="danger" />}
        </div>
      )}

      <div className="nav-tabs resource-tabs">
        <button className={`nav-tab ${activeTab === "vm" ? "active" : ""}`} onClick={() => switchTab("vm")}>
          Виртуальные машины
        </button>
        <button className={`nav-tab ${activeTab === "lxc" ? "active" : ""}`} onClick={() => switchTab("lxc")}>
          LXC-контейнеры
        </button>
      </div>

      {showForm && (
        <form onSubmit={onCreate} className="card create-form">
          {error && <div className="error-box">{error}</div>}
          <div className="form-section">
            <label className="form-label">
              {activeTab === "vm" ? "Шаблон виртуальной машины" : "Архивный LXC-шаблон"}
            </label>
            <select value={templateId} onChange={(event) => setTemplateId(event.target.value)} className="preset-select" required>
              <option value="" disabled>{typeTemplates.length ? "Выберите шаблон" : "Шаблоны не найдены"}</option>
              {typeTemplates.map((template) => (
                <option key={template.id} value={template.id}>
                  {template.name} · {template.cores} vCPU · {template.memory_mb} МБ · {template.disk_gb} ГБ
                </option>
              ))}
            </select>
          </div>

          {activeTab === "vm" && (
            <div className="preset-buttons">
              {PRESETS.map((preset) => {
                const available = Boolean(matchPreset(typeTemplates, preset));
                return (
                  <button
                    key={preset.key}
                    type="button"
                    disabled={!available}
                    className={`preset-btn ${selectedPreset === preset.key ? "active" : ""}`}
                    onClick={() => {
                      setSelectedPreset(preset.key);
                      const match = matchPreset(typeTemplates, preset);
                      if (match) setTemplateId(String(match.id));
                    }}
                  >
                    {preset.label}
                  </button>
                );
              })}
            </div>
          )}

          <div className="form-row">
            <div className="field"><label>Имя сервера</label><input value={name} onChange={(event) => setName(event.target.value)} placeholder={activeTab === "lxc" ? "debian" : "my-server"} required /></div>
            <div className="field"><label>{activeTab === "lxc" ? "Пользователь root" : "Пользователь"}</label><input value={ciuser} onChange={(event) => setCiuser(event.target.value)} disabled={activeTab === "lxc"} /></div>
            <div className="field"><label>Новый пароль</label><input type="password" value={cipassword} onChange={(event) => setCipassword(event.target.value)} placeholder="необязательно" /></div>
          </div>
          {activeTab === "lxc" && <p className="page-sub">Для архивного шаблона Proxmox создаст новый root-пароль.</p>}
          {error && <div className="error-box">{error}</div>}
          <button type="submit" disabled={busy || !templateId || !name.trim()} className="btn btn-primary submit-btn">
            {busy ? "⏳ Создаём…" : activeTab === "lxc" ? "🚀 Создать контейнер" : "🚀 Развернуть VM"}
          </button>
        </form>
      )}

      {loading ? <div className="empty-state">Загрузка...</div> : visibleInstances.length === 0 ? (
        <div className="empty-state">
          <div className="empty-icon">☁️</div>
          <div className="empty-title">Нет {activeTab === "lxc" ? "LXC-контейнеров" : "виртуальных машин"}</div>
          <div className="empty-sub">Нажмите «+ Новый VPS», чтобы создать ресурс</div>
        </div>
      ) : (
        <div className="instance-grid">
          {visibleInstances.map((instance) => <InstanceCard key={instance.id} instance={instance} onAction={onAction} onDelete={onDelete} />)}
        </div>
      )}
    </div>
  );
}
