"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { Boxes, Calendar, Clock, Play, Square, Trash2, User as UserIcon, RefreshCw, LogIn, Settings, AlertCircle, RotateCcw } from "lucide-react";
import { formatDate, instancePublicUrl } from "@/lib/utils";

type InstanceStatus = "CREATING" | "RUNNING" | "STOPPED" | "DELETED" | "ERROR";
type UserRole = "USER" | "ADMIN";

interface User {
  id: string;
  full_name?: string;
  username: string;
  email: string;
  role: UserRole;
}

interface Instance {
  id: string;
  name: string;
  slug: string;
  app_type: string;
  subdomain: string;
  status: InstanceStatus;
  port?: number;
  created_at: string;
  updated_at: string;
  deleted_at?: string;
  scheduled_deletion_date?: string;
  restored_at?: string;
  deleted_by?: string;
  restored_by?: string;
  user: User;
}

interface AdminSettings {
  id: string;
  instanceRetentionDays: number;
}

export default function AdminManagedInstancesPage() {
  const [instances, setInstances] = useState<Instance[]>([]);
  const [settings, setSettings] = useState<AdminSettings | null>(null);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const [filter, setFilter] = useState<"all" | "running" | "stopped" | "deleted">("all");
  const [showDeleted, setShowDeleted] = useState(true);
  const [message, setMessage] = useState<{ type: "success" | "error"; text: string } | null>(null);

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

  const fetchInstances = async () => {
    try {
      const res = await fetch("/api/admin/instances");
      if (res.ok) {
        const data = await res.json();
        setInstances(data.instances || []);
      }
    } catch (err) {
      console.error("Failed to fetch instances:", err);
    } finally {
      setLoading(false);
    }
  };

  const fetchSettings = async () => {
    try {
      const res = await fetch("/api/admin/settings/retention");
      if (res.ok) {
        const data = await res.json();
        setSettings(data.settings);
      }
    } catch (err) {
      console.error("Failed to fetch settings:", err);
    }
  };

  const showMessage = (type: "success" | "error", text: string) => {
    setMessage({ type, text });
    setTimeout(() => setMessage(null), 5000);
  };

  const handleAction = async (instance_id: string, action: string, confirmMessage?: string) => {
    if (confirmMessage && !confirm(confirmMessage)) return;

    setActionLoading(instance_id);
    try {
      const res = await fetch(`/api/admin/instances/${instance_id}/${action}`, {
        method: action === "force-delete" ? "DELETE" : "POST"
      });

      const data = await res.json();

      if (res.ok) {
        showMessage("success", data.message || "Action completed successfully");
        await fetchInstances();
      } else {
        showMessage("error", data.error || "Action failed");
      }
    } catch (err) {
      showMessage("error", "Failed to perform action");
    } finally {
      setActionLoading(null);
    }
  };

  const handleLoginAsUser = async (instance_id: string) => {
    setActionLoading(instance_id);
    try {
      const res = await fetch(`/api/admin/instances/${instance_id}/login-as-user`, {
        method: "POST"
      });

      const data = await res.json();

      if (res.ok) {
        // Redirect to user dashboard with impersonation token
        window.location.href = data.redirectUrl;
      } else {
        showMessage("error", data.error || "Failed to login as user");
      }
    } catch (error) {
      showMessage("error", "Failed to login as user");
    } finally {
      setActionLoading(null);
    }
  };

  const handleJarvisRestart = async (instance_id: string) => {
    setActionLoading(instance_id);
    try {
      const res = await fetch(`/api/jarvis/${instance_id}/restart`, { method: "POST" });
      const data = await res.json();
      if (res.ok) {
        showMessage("success", data.message || "Jarvis instance restarted.");
      } else {
        showMessage("error", data.error || "Restart failed.");
      }
    } catch {
      showMessage("error", "Failed to restart instance.");
    } finally {
      setActionLoading(null);
    }
  };

  const updateRetentionDays = async (days: number) => {
    try {
      const res = await fetch("/api/admin/settings/retention", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ days })
      });

      const data = await res.json();

      if (res.ok) {
        showMessage("success", "Retention days updated successfully");
        setSettings(data.settings);
      } else {
        showMessage("error", data.error || "Failed to update settings");
      }
    } catch (error) {
      showMessage("error", "Failed to update settings");
    }
  };

  const getStatusColor = (status: InstanceStatus) => {
    switch (status) {
      case "RUNNING": return "bg-green-100 text-green-800";
      case "STOPPED": return "bg-amber-100 text-amber-800";
      case "DELETED": return "bg-red-100 text-red-800";
      case "ERROR": return "bg-red-100 text-red-800";
      default: return "bg-gray-100 text-gray-800";
    }
  };

  const getStatusIcon = (status: InstanceStatus) => {
    switch (status) {
      case "RUNNING": return <Play size={14} />;
      case "STOPPED": return <Square size={14} />;
      case "DELETED": return <Trash2 size={14} />;
      default: return null;
    }
  };

  const filteredInstances = instances.filter(instance => {
    if (filter === "all") return showDeleted || instance.status !== "DELETED";
    if (filter === "deleted") return instance.status === "DELETED";
    return instance.status === filter.toUpperCase() && (showDeleted || instance.status !== "DELETED");
  });

  const stats = {
    total: instances.length,
    running: instances.filter(i => i.status === "RUNNING").length,
    stopped: instances.filter(i => i.status === "STOPPED").length,
    deleted: instances.filter(i => i.status === "DELETED").length,
    error: instances.filter(i => i.status === "ERROR").length,
    pendingDeletion: instances.filter(i => i.scheduled_deletion_date && new Date(i.scheduled_deletion_date) <= new Date()).length
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <RefreshCw className="animate-spin text-brand" size={32} />
      </div>
    );
  }

  return (
    <div className="space-y-6">
        {/* Message */}
        {message && (
          <div className={`p-4 rounded-md ${message.type === "success" ? "bg-green-50 text-green-800" : "bg-red-50 text-red-800"}`}>
            {message.text}
          </div>
        )}

        {/* Stats Cards */}
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4">
          <div className="bg-white p-4 rounded-lg border">
            <div className="flex items-center gap-3">
              <Boxes className="text-blue-600" size={20} />
              <div>
                <p className="text-2xl font-bold">{stats.total}</p>
                <p className="text-xs text-slate-600">Total</p>
              </div>
            </div>
          </div>
          <div className="bg-white p-4 rounded-lg border">
            <div className="flex items-center gap-3">
              <Play className="text-green-600" size={20} />
              <div>
                <p className="text-2xl font-bold">{stats.running}</p>
                <p className="text-xs text-slate-600">Running</p>
              </div>
            </div>
          </div>
          <div className="bg-white p-4 rounded-lg border">
            <div className="flex items-center gap-3">
              <Square className="text-amber-600" size={20} />
              <div>
                <p className="text-2xl font-bold">{stats.stopped}</p>
                <p className="text-xs text-slate-600">Stopped</p>
              </div>
            </div>
          </div>
          <div className="bg-white p-4 rounded-lg border">
            <div className="flex items-center gap-3">
              <Trash2 className="text-red-600" size={20} />
              <div>
                <p className="text-2xl font-bold">{stats.deleted}</p>
                <p className="text-xs text-slate-600">Deleted</p>
              </div>
            </div>
          </div>
          <div className="bg-white p-4 rounded-lg border">
            <div className="flex items-center gap-3">
              <AlertCircle className="text-red-600" size={20} />
              <div>
                <p className="text-2xl font-bold">{stats.error}</p>
                <p className="text-xs text-slate-600">Error</p>
              </div>
            </div>
          </div>
          <div className="bg-white p-4 rounded-lg border">
            <div className="flex items-center gap-3">
              <Clock className="text-purple-600" size={20} />
              <div>
                <p className="text-2xl font-bold">{stats.pendingDeletion}</p>
                <p className="text-xs text-slate-600">Pending Delete</p>
              </div>
            </div>
          </div>
        </div>

        {/* Retention Settings */}
        {settings && (
          <div className="bg-white p-4 rounded-lg border">
            <div className="flex items-center justify-between">
              <div>
                <h3 className="font-semibold text-slate-900">Auto-Deletion Retention</h3>
                <p className="text-sm text-slate-600">
                  Days before stopped/deleted instances are permanently deleted
                </p>
              </div>
              <div className="flex items-center gap-3">
                <input
                  type="number"
                  min="1"
                  max="90"
                  value={settings.instanceRetentionDays}
                  onChange={(e) => updateRetentionDays(parseInt(e.target.value) || 7)}
                  className="w-20 px-3 py-2 border rounded-md text-center"
                />
                <span className="text-sm text-slate-600">days</span>
              </div>
            </div>
          </div>
        )}

        {/* Filters */}
        <div className="bg-white p-4 rounded-lg border">
          <div className="flex flex-wrap items-center gap-4">
            <div className="flex items-center gap-2">
              <label className="text-sm font-medium text-slate-700">Status:</label>
              <select
                value={filter}
                onChange={(e) => setFilter(e.target.value as "all" | "running" | "stopped" | "deleted")}
                className="px-3 py-2 border rounded-md text-sm"
              >
                <option value="all">All</option>
                <option value="running">Running</option>
                <option value="stopped">Stopped</option>
                <option value="deleted">Deleted</option>
              </select>
            </div>
            <label className="flex items-center gap-2 text-sm">
              <input
                type="checkbox"
                checked={showDeleted}
                onChange={(e) => setShowDeleted(e.target.checked)}
                className="rounded"
              />
              Show deleted instances
            </label>
          </div>
        </div>

        {/* Instances Table */}
        <div className="bg-white rounded-lg border overflow-hidden">
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-slate-50 border-b">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Instance</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Owner</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Status</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Port</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Created</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Deleted</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Scheduled Deletion</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-slate-500 uppercase">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-200">
                {filteredInstances.map((instance) => (
                  <tr
                    key={instance.id}
                    className={`hover:bg-opacity-50 ${
                      instance.status === "DELETED"
                        ? "bg-red-50 hover:bg-red-100"
                        : "hover:bg-slate-50"
                    }`}
                  >
                    <td className="px-4 py-3">
                      <div>
                        <p className="font-medium text-slate-900">{instance.name}</p>
                        <p className="text-xs text-slate-500">{instance.slug}</p>
                        <a
                          href={instancePublicUrl(instance.subdomain)}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="text-xs text-blue-600 hover:underline"
                        >
                          {instance.subdomain}
                        </a>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        <UserIcon size={14} className="text-slate-400" />
                        <div>
                          <p className="text-sm font-medium text-slate-900">{instance.user.full_name || instance.user.username}</p>
                          <p className="text-xs text-slate-500">{instance.user.email}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(instance.status)}`}>
                        {getStatusIcon(instance.status)}
                        {instance.status}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-sm text-slate-600">{instance.port || "-"}</td>
                    <td className="px-4 py-3 text-sm">
                      <div className={`flex items-center gap-1 ${instance.status === "DELETED" ? "text-slate-500" : "text-slate-600"}`}>
                        <Calendar size={12} />
                        {formatDate(instance.created_at)}
                      </div>
                    </td>
                    <td className="px-4 py-3 text-sm">
                      {instance.deleted_at ? (
                        <div className="flex items-center gap-1 text-red-600 font-medium">
                          <Trash2 size={12} />
                          {formatDate(instance.deleted_at)}
                        </div>
                      ) : (
                        <span className="text-slate-400">-</span>
                      )}
                    </td>
                    <td className="px-4 py-3 text-sm">
                      {instance.scheduled_deletion_date ? (
                        <div className="flex items-center gap-1 text-red-600">
                          <Clock size={12} />
                          {formatDate(instance.scheduled_deletion_date)}
                        </div>
                      ) : "-"}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        {instance.status === "RUNNING" && (
                          <>
                            <button
                              onClick={() => handleAction(instance.id, "stop", `Stop instance "${instance.name}"?`)}
                              disabled={actionLoading === instance.id}
                              className="p-1.5 rounded hover:bg-amber-100 text-amber-600 disabled:opacity-50"
                              title="Stop instance"
                            >
                              <Square size={16} />
                            </button>
                            <button
                              onClick={() => handleAction(instance.id, "delete", `Delete instance "${instance.name}"?`)}
                              disabled={actionLoading === instance.id}
                              className="p-1.5 rounded hover:bg-red-100 text-red-600 disabled:opacity-50"
                              title="Delete instance"
                            >
                              <Trash2 size={16} />
                            </button>
                            {instance.app_type === "jarvis" && (
                              <button
                                onClick={() => handleJarvisRestart(instance.id)}
                                disabled={actionLoading === instance.id}
                                className="p-1.5 rounded hover:bg-blue-100 text-blue-600 disabled:opacity-50"
                                title="Restart Jarvis container"
                              >
                                <RotateCcw size={16} />
                              </button>
                            )}
                          </>
                        )}
                        {(instance.status === "STOPPED" || instance.status === "DELETED") && (
                          <>
                            <button
                              onClick={() => handleAction(instance.id, "restore")}
                              disabled={actionLoading === instance.id}
                              className="p-1.5 rounded hover:bg-green-100 text-green-600 disabled:opacity-50"
                              title="Restore instance"
                            >
                              <Play size={16} />
                            </button>
                            <button
                              onClick={() => handleAction(instance.id, "force-delete", `Permanently delete "${instance.name}"? This cannot be undone.`)}
                              disabled={actionLoading === instance.id}
                              className="p-1.5 rounded hover:bg-red-100 text-red-600 disabled:opacity-50"
                              title="Force delete permanently"
                            >
                              <Trash2 size={16} />
                            </button>
                          </>
                        )}
                        <button
                          onClick={() => handleLoginAsUser(instance.id)}
                          disabled={actionLoading === instance.id}
                          className="p-1.5 rounded hover:bg-blue-100 text-blue-600 disabled:opacity-50"
                          title="Login as user"
                        >
                          <LogIn size={16} />
                        </button>
                        <a
                          href={`https://${instance.subdomain}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          className="p-1.5 rounded hover:bg-slate-100 text-slate-600"
                          title="Open instance"
                        >
                          <Boxes size={16} />
                        </a>
                      </div>
                    </td>
                  </tr>
                ))}
                {filteredInstances.length === 0 && (
                  <tr>
                    <td colSpan={8} className="px-4 py-8 text-center text-slate-500">
                      No instances found
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
      </div>
    </div>
  );
}
