"use client";

import { useState, useEffect } from "react";
import { DashboardHeader } from "@/components/dashboard/header";
import { Cpu, Plus, Trash2, ExternalLink, Loader2, AlertCircle, RotateCcw } from "lucide-react";
import type { Locale } from "@/lib/i18n";

type Instance = {
  id: number;
  name: string;
  slug: string;
  subdomain: string;
  status: string;
  port: number | null;
  created_at: string;
  last_error?: string | null;
  deploy_payload?: { hudToken?: string } | null;
};

const labels = {
  en: {
    title: "Jarvis AI",
    subtitle: "Iron-Man HUD for your Hermes AI agent. Voice, holographic panels, and full agent control.",
    create: "Create Instance",
    creating: "Creating...",
    launch: "Launch",
    delete: "Delete",
    noInstances: "No Jarvis instances yet. Create one to get started.",
    status: "Status",
    created: "Created",
    error: "Error",
    maxReached: "Maximum instances reached",
    back: "Back to Dashboard",
    destroying: "Destroying...",
  },
  ar: {
    title: "جارفيس AI",
    subtitle: "واجهة الرجل الحديدي لوكيل Hermes الذكي. صوت، لوحات هولوغرافية، وتحكم كامل.",
    create: "إنشاء مثيل",
    creating: "جارٍ الإنشاء...",
    launch: "فتح",
    delete: "حذف",
    noInstances: "لا توجد مثيلات Jarvis بعد. أنشئ واحداً للبدء.",
    status: "الحالة",
    created: "تاريخ الإنشاء",
    error: "خطأ",
    maxReached: "تم الوصول للحد الأقصى",
    back: "عودة للوحة التحكم",
    destroying: "جارٍ الحذف...",
  },
};

export default function JarvisDashboardPage() {
  const locale = "en" as Locale;
  const t = labels[locale];
  const [instances, setInstances] = useState<Instance[]>([]);
  const [hermesInstances, setHermesInstances] = useState<{ slug: string; name: string }[]>([]);
  const [selectedHermes, setSelectedHermes] = useState("");
  const [loading, setLoading] = useState(true);
  const [creating, setCreating] = useState(false);
  const [destroying, setDestroying] = useState<number | null>(null);
  const [restarting, setRestarting] = useState<number | null>(null);
  const [name, setName] = useState("");
  const [error, setError] = useState<string | null>(null);

  const fetchInstances = async () => {
    try {
      const [jarvisRes, allInstancesRes] = await Promise.all([
        fetch("/api/jarvis/instances"),
        fetch("/api/instances"),
      ]);
      if (jarvisRes.ok) {
        const data = await jarvisRes.json();
        setInstances(data.instances || []);
      }
      if (allInstancesRes.ok) {
        const data = await allInstancesRes.json();
        const hermes = (data.instances || []).filter((i: { app_type: string }) => i.app_type === "hermes");
        setHermesInstances(hermes);
        if (hermes.length > 0) {
          setSelectedHermes(hermes[0].slug);
        }
      }
    } catch {
      setError("Failed to load instances.");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchInstances();
  }, []);

  const handleCreate = async () => {
    if (!name.trim() || !selectedHermes) return;
    setCreating(true);
    setError(null);
    try {
      const res = await fetch("/api/jarvis/instances", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name: name.trim(), hermesSlug: selectedHermes }),
      });
      const data = await res.json();
      if (res.ok) {
        setName("");
        setInstances((prev) => [data.instance, ...prev]);
        pollInstance(data.instance.id);
      } else {
        setError(data.error || "Failed to create instance.");
      }
    } catch {
      setError("Failed to create instance.");
    } finally {
      setCreating(false);
    }
  };

  const pollInstance = (id: number) => {
    const interval = setInterval(async () => {
      try {
        const res = await fetch("/api/jarvis/instances");
        if (res.ok) {
          const data = await res.json();
          const updated = data.instances.find((i: Instance) => i.id === id);
          if (updated && updated.status !== "CREATING") {
            setInstances(data.instances || []);
            clearInterval(interval);
          }
        }
      } catch {
        clearInterval(interval);
      }
    }, 3000);
    setTimeout(() => clearInterval(interval), 120000);
  };

  const handleDelete = async (id: number) => {
    if (!confirm("Delete this Jarvis instance? All data will be lost.")) return;
    setDestroying(id);
    try {
      const res = await fetch(`/api/jarvis/instances?id=${id}`, { method: "DELETE" });
      if (res.ok) {
        setInstances((prev) => prev.filter((i) => i.id !== id));
      }
    } catch {
      setError("Failed to delete instance.");
    } finally {
      setDestroying(null);
    }
  };

  const handleRestart = async (id: number) => {
    setRestarting(id);
    try {
      const res = await fetch(`/api/jarvis/${id}/restart`, { method: "POST" });
      if (!res.ok) {
        const data = await res.json();
        setError(data.error || "Restart failed.");
      }
    } catch {
      setError("Failed to restart instance.");
    } finally {
      setRestarting(null);
    }
  };

  const statusBadge = (status: string) => {
    const colors: Record<string, string> = {
      CREATING: "bg-blue-100 text-blue-800",
      RUNNING: "bg-emerald-100 text-emerald-800",
      ERROR: "bg-red-100 text-red-800",
    };
    return (
      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${colors[status] || "bg-gray-100 text-gray-800"}`}>
        {status}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-slate-50">
        <DashboardHeader locale={locale} />
        <div className="flex items-center justify-center h-96">
          <Loader2 className="animate-spin text-brand" size={32} />
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-slate-50">
      <DashboardHeader locale={locale} />
      <div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="flex items-center justify-between mb-8">
          <div>
            <div className="flex items-center gap-3">
              <Cpu size={28} className="text-brand" />
              <h1 className="text-2xl font-bold text-slate-900">{t.title}</h1>
            </div>
            <p className="mt-1 text-sm text-slate-600">{t.subtitle}</p>
          </div>
          <div className="flex items-center gap-3">
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Instance name"
              className="px-3 py-2 border rounded-lg text-sm w-44"
              onKeyDown={(e) => e.key === "Enter" && handleCreate()}
            />
            <select
              value={selectedHermes}
              onChange={(e) => setSelectedHermes(e.target.value)}
              className="px-3 py-2 border rounded-lg text-sm w-44 bg-white"
            >
              {hermesInstances.length === 0 && <option value="">No Hermes instances</option>}
              {hermesInstances.map((h) => (
                <option key={h.slug} value={h.slug}>{h.name}</option>
              ))}
            </select>
            <button
              onClick={handleCreate}
              disabled={creating || !name.trim() || !selectedHermes || instances.length >= 3}
              className="inline-flex items-center gap-2 px-4 py-2 bg-brand text-white rounded-lg hover:opacity-90 disabled:opacity-50 text-sm font-medium"
            >
              {creating ? <Loader2 size={16} className="animate-spin" /> : <Plus size={16} />}
              {creating ? t.creating : t.create}
            </button>
          </div>
        </div>

        {error && (
          <div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg flex items-center gap-2 text-red-700 text-sm">
            <AlertCircle size={16} />
            {error}
          </div>
        )}

        {instances.length === 0 ? (
          <div className="text-center py-16 bg-white rounded-xl border border-dashed">
            <Cpu size={48} className="mx-auto text-slate-300 mb-4" />
            <p className="text-slate-500">{t.noInstances}</p>
          </div>
        ) : (
          <div className="grid gap-4 md:grid-cols-2">
            {instances.map((instance) => (
              <div key={instance.id} className="bg-white rounded-xl border p-5 hover:shadow-md transition-shadow">
                <div className="flex items-start justify-between mb-3">
                  <div>
                    <h3 className="font-semibold text-slate-900">{instance.name}</h3>
                    <p className="text-xs text-slate-500 mt-0.5">{instance.slug}</p>
                  </div>
                  {statusBadge(instance.status)}
                </div>
                <div className="text-xs text-slate-500 space-y-1 mb-4">
                  <p>Port: {instance.port || "-"}</p>
                  <p>{t.created}: {new Date(instance.created_at).toLocaleDateString()}</p>
                  {instance.deploy_payload?.hudToken && (
                    <p className="font-mono text-amber-700 bg-amber-50 px-1.5 py-0.5 rounded inline-block mt-1">
                      ACCESS CODE: {instance.deploy_payload.hudToken}
                    </p>
                  )}
                </div>
                {instance.status === "ERROR" && instance.last_error && (
                  <div className="mb-3 p-2 bg-red-50 rounded text-xs text-red-600 break-words">
                    {instance.last_error}
                  </div>
                )}
                <div className="flex items-center gap-2">
                  {instance.status === "RUNNING" && (
                    <a
                      href={`https://${instance.subdomain}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-brand text-white rounded-lg text-sm hover:opacity-90"
                    >
                      <ExternalLink size={14} />
                      {t.launch}
                    </a>
                  )}
                  {instance.status === "RUNNING" && (
                    <button
                      onClick={() => handleRestart(instance.id)}
                      disabled={restarting === instance.id}
                      className="inline-flex items-center gap-1.5 px-3 py-1.5 text-blue-600 border border-blue-200 rounded-lg text-sm hover:bg-blue-50 disabled:opacity-50"
                    >
                      {restarting === instance.id ? <Loader2 size={14} className="animate-spin" /> : <RotateCcw size={14} />}
                      Restart
                    </button>
                  )}
                  {instance.status !== "DELETED" && (
                    <button
                      onClick={() => handleDelete(instance.id)}
                      disabled={destroying === instance.id}
                      className="inline-flex items-center gap-1.5 px-3 py-1.5 text-red-600 border border-red-200 rounded-lg text-sm hover:bg-red-50 disabled:opacity-50"
                    >
                      {destroying === instance.id ? <Loader2 size={14} className="animate-spin" /> : <Trash2 size={14} />}
                      {destroying === instance.id ? t.destroying : t.delete}
                    </button>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
