import React, { useEffect, useState, useCallback, useMemo } from "react";
import { Link } from "react-router-dom";
import { api } from "../api.js";
import InstanceCard from "../components/InstanceCard.jsx";

const UbuntuLogo = () => (
  <svg viewBox="0 0 64 64" width="28" height="28"><circle cx="32" cy="32" r="28" fill="#E95420"/><circle cx="32" cy="32" r="22" fill="#fff"/><circle cx="32" cy="32" r="14" fill="#E95420"/><g stroke="#fff" strokeWidth="3" fill="none"><line x1="32" y1="10" x2="32" y2="18"/><line x1="32" y1="46" x2="32" y2="54"/><line x1="10" y1="32" x2="18" y2="32"/><line x1="46" y1="32" x2="54" y2="32"/></g></svg>
);
const DebianLogo = () => (
  <svg viewBox="0 0 64 64" width="28" height="28"><circle cx="32" cy="32" r="28" fill="#A81D33"/><path d="M32 8c-5 0-10 2-14 6l6 10c2-2 5-3 8-3 7 0 13 6 13 13 0 7-6 13-13 13-3 0-6-1-8-3l-6 10c4 4 9 6 14 6 13 0 24-11 24-24S45 8 32 8z" fill="#fff" opacity="0.9"/></svg>
);
const CentOSLogo = () => (
  <svg viewBox="0 0 64 64" width="28" height="28"><circle cx="32" cy="32" r="28" fill="#932279"/><path d="M32 12l-12 8v16l12 8 12-8V20L32 12zm0 6l7 5v10l-7 5-7-5V23l7-5z" fill="#fff" opacity="0.9"/></svg>
);

const OS_OPTIONS = [
  { key: "ubuntu", label: "Ubuntu", desc: "Универсальный", logo: UbuntuLogo },
  { key: "debian", label: "Debian", desc: "Стабильный", logo: DebianLogo },
  { key: "centos", label: "CentOS", desc: "Корпоративный", logo: CentOSLogo },
];
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 filterByOS(templates, os) {
  if (!os) return templates;
  return templates.filter((template) => template.name.toLowerCase().includes(os));
}

function matchPreset(templates, preset) {
  const exact = templates.find((template) => template.cores === preset.cpu && template.memory_mb === preset.ram && template.disk_gb === preset.disk);
  if (exact) return exact;
  return 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", icon }) {
  return <div className={`stat-card stat-${tone}`}><div className="stat-card-icon">{icon}</div><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 [showForm, setShowForm] = useState(false);
  const [guestType, setGuestType] = useState("vm");           // "vm" | "lxc" — задаётся кнопкой в шапке, внутри формы не меняется
  const [name, setName] = useState("");
  const [ciuser, setCiuser] = useState("ubuntu");
  const [cipassword, setCipassword] = useState("");
  const [templateId, setTemplateId] = useState("");
  const [selectedOS, setSelectedOS] = useState("ubuntu");
  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 = useMemo(
    () => templates.filter((t) => t.guest_type === guestType),
    [templates, guestType]
  );
  const osTemplates = useMemo(
    () => filterByOS(typeTemplates, selectedOS),
    [typeTemplates, selectedOS]
  );

  // При смене типа — сбросить выбор тарифа и подобрать доступную ОС.
  useEffect(() => {
    setTemplateId("");
    setSelectedPreset(null);
    if (!OS_OPTIONS.some((os) => os.key === selectedOS && filterByOS(typeTemplates, os.key).length > 0)) {
      const firstAvailable = OS_OPTIONS.find((os) => filterByOS(typeTemplates, os.key).length > 0);
      setSelectedOS(firstAvailable?.key || "ubuntu");
    }
  }, [guestType, typeTemplates]);

  // Авто-выбор первого подходящего шаблона при изменении фильтров.
  useEffect(() => {
    if (selectedPreset) {
      const preset = PRESETS.find((item) => item.key === selectedPreset);
      const match = preset ? matchPreset(osTemplates, preset) : null;
      if (match) setTemplateId(String(match.id));
    } else if (osTemplates.length) {
      setTemplateId(String(osTemplates[0].id));
    } else {
      setTemplateId("");
    }
  }, [selectedOS, selectedPreset, osTemplates]);

  // Открыть форму для конкретного типа — VM или LXC.
  const openForm = (type) => {
    setGuestType(type);
    setName("");
    setCipassword("");
    setSelectedPreset(null);
    setShowForm(true);
  };

  const closeForm = () => {
    setShowForm(false);
    setError("");
  };

  async function onCreate(event) {
    event.preventDefault();
    if (busy) return;
    setError("");
    setBusy(true);
    try {
      const isLxc = guestType === "lxc";
      await api.createInstance({
        name,
        template_id: Number(templateId),
        ciuser: isLxc ? "" : (ciuser || ""),
        cipassword: cipassword || "",
      });
      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("Удалить VPS?")) 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,
  };

  const isLxc = guestType === "lxc";
  const hasTypeTemplates = typeTemplates.length > 0;

  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>
        {!showForm && (
          <div className="dashboard-actions">
            <button className="btn" onClick={() => openForm("vm")}>🖥 + Новый VM</button>
            <button className="btn btn-primary" onClick={() => openForm("lxc")}>📦 + Новый LXC</button>
          </div>
        )}
        {showForm && (
          <button className="btn" onClick={closeForm}>✕ Отмена</button>
        )}
      </div>

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

      {showForm && (
        <form onSubmit={onCreate} className="card create-form">
          {error && <div className="error-box">{error}</div>}

          {/* Статический заголовок типа — переключатель убран, тип задаётся
              только кнопкой в шапке при открытии формы. */}
          <div className="form-type-banner">
            {isLxc ? (
              <>
                <span className="form-type-banner-icon">📦</span>
                <span className="form-type-banner-text">
                  Создаём <strong>LXC-контейнер</strong> · пользователь <code>root</code> · пароль задаёте сами
                </span>
              </>
            ) : (
              <>
                <span className="form-type-banner-icon">🖥</span>
                <span className="form-type-banner-text">
                  Создаём <strong>виртуальную машину</strong> · cloud-init · любой пользователь
                </span>
              </>
            )}
          </div>

          <div className="form-row">
            <div className="field" style={{ flex: 2 }}><label>Имя сервера</label><input value={name} onChange={(event) => setName(event.target.value)} placeholder="my-server" required /></div>
            {isLxc ? (
              <div className="field"><label>Пользователь</label><input value="root" disabled readOnly title="В LXC-контейнере всегда root" /></div>
            ) : (
              <div className="field"><label>Пользователь</label><input value={ciuser} onChange={(event) => setCiuser(event.target.value)} placeholder="ubuntu" /></div>
            )}
            <div className="field"><label>Пароль</label><input type="password" value={cipassword} onChange={(event) => setCipassword(event.target.value)} placeholder="••••••" required={isLxc} title={isLxc ? "Задайте root-пароль для LXC" : "Пароль для cloud-init"} /></div>
          </div>

          {/* Система и тариф — только если есть шаблоны этого типа. */}
          {!hasTypeTemplates ? (
            <div className="form-section">
              <div className="empty-box">
                <div className="empty-box-icon">📦</div>
                <div className="empty-box-title">Нет шаблонов для {isLxc ? "LXC-контейнеров" : "VM (виртуальных машин)"}</div>
                <div className="empty-box-sub">
                  Перейдите в раздел <strong>«Шаблоны»</strong> слева →
                  нажмите <strong>«🔍 Найти шаблоны на Proxmox»</strong> →
                  импортируйте нужный шаблон. После этого он появится здесь.
                </div>
              </div>
            </div>
          ) : (
            <>
              <div className="form-section">
                <label className="form-label">Система</label>
                <div className="os-grid">{OS_OPTIONS.map((os) => {
                  const active = selectedOS === os.key;
                  const available = filterByOS(typeTemplates, os.key).length > 0;
                  return (
                    <button
                      key={os.key}
                      type="button"
                      disabled={!available}
                      onClick={() => { setSelectedOS(os.key); setSelectedPreset(null); }}
                      className={`os-card${active ? " active" : ""}${!available ? " disabled" : ""}`}
                    >
                      <os.logo />
                      <div>
                        <div className="os-name">{os.label}</div>
                        <div className="os-desc">{available ? os.desc : "нет шаблонов"}</div>
                      </div>
                    </button>
                  );
                })}</div>
              </div>

              <div className="form-section">
                <label className="form-label">Тариф</label>
                <div className="preset-row">
                  <select
                    value={templateId}
                    onChange={(event) => setTemplateId(event.target.value)}
                    className="preset-select"
                  >
                    {osTemplates.length === 0 ? (
                      <option value="">Нет шаблонов для «{OS_OPTIONS.find((o) => o.key === selectedOS)?.label}»</option>
                    ) : (
                      osTemplates.map((template) => (
                        <option key={template.id} value={template.id}>
                          {template.name} · {template.cores} vCPU · {template.memory_mb} MB · {template.disk_gb} GB
                        </option>
                      ))
                    )}
                  </select>
                  <div className="preset-buttons">{PRESETS.map((preset) => {
                    const match = matchPreset(osTemplates, preset);
                    const available = Boolean(match);
                    return (
                      <button
                        key={preset.key}
                        type="button"
                        disabled={!available}
                        onClick={() => { setSelectedPreset(preset.key); if (match) setTemplateId(String(match.id)); }}
                        className={`preset-btn${selectedPreset === preset.key ? " active" : ""}${!available ? " disabled" : ""}`}
                      >
                        <div className="preset-label">{preset.label}</div>
                        <div className="preset-status">{available ? "✓" : "—"}</div>
                      </button>
                    );
                  })}</div>
                </div>
              </div>
            </>
          )}

          <button
            type="submit"
            disabled={busy || !templateId || !name || (isLxc && !cipassword) || !hasTypeTemplates}
            className="btn btn-primary submit-btn"
          >
            {busy ? "⏳ Создаём..." : (isLxc ? "📦 Создать LXC" : "🚀 Развернуть VM")}
          </button>
        </form>
      )}

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

const IconServer = () => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="20" height="6" rx="1"/><rect x="2" y="15" width="20" height="6" rx="1"/><line x1="6" y1="6" x2="6.01" y2="6"/><line x1="6" y1="18" x2="6.01" y2="18"/></svg>;
const IconPlay = () => <svg viewBox="0 0 24 24" width="22" height="22" fill="22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><polygon points="6 4 20 12 6 20 6 4"/></svg>;
const IconStop = () => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><rect x="5" y="5" width="14" height="14" rx="1"/></svg>;
const IconAlert = () => <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>;