"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { doc, onSnapshot } from "firebase/firestore";
import { db } from "@/lib/firebase";
import { useSystems } from "@/lib/useSystems";
import { useCalls } from "@/lib/useCalls";
import { StatusBadge } from "@/components/StatusBadge";
import { NodeConfigModal } from "@/components/NodeConfigModal";
import { CallRow } from "@/components/CallRow";
import { useAuth } from "@/components/AuthProvider";
import { c2api } from "@/lib/c2api";
import type { NodeRecord } from "@/lib/types";

function ApprovalBadge({ status }: { status: string | null }) {
  if (status === "approved") return (
    <span className="text-xs text-green-400 bg-green-400/10 px-2 py-0.5 rounded font-mono">Approved</span>
  );
  if (status === "rejected") return (
    <span className="text-xs text-red-400 bg-red-400/10 px-2 py-0.5 rounded font-mono">Rejected</span>
  );
  return (
    <span className="text-xs text-yellow-400 bg-yellow-400/10 px-2 py-0.5 rounded font-mono">Pending approval</span>
  );
}

function DiscordJoinModal({
  nodeId,
  onClose,
}: {
  nodeId: string;
  onClose: () => void;
}) {
  const [guildId, setGuildId] = useState("");
  const [channelId, setChannelId] = useState("");
  const [sending, setSending] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSending(true);
    setError(null);
    try {
      await c2api.sendCommand(nodeId, {
        action: "discord_join",
        guild_id: guildId,
        channel_id: channelId,
      });
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to send join command.");
    } finally {
      setSending(false);
    }
  }

  return (
    <div className="fixed inset-0 bg-black/60 flex items-center justify-center z-50 p-4">
      <form
        onSubmit={handleSubmit}
        className="bg-gray-900 border border-gray-700 rounded-xl p-6 space-y-4 font-mono w-full max-w-sm"
      >
        <h3 className="text-white font-semibold">Join Discord Voice</h3>
        <div>
          <label className="text-xs text-gray-400 block mb-1">Server ID (Guild)</label>
          <input
            value={guildId}
            onChange={(e) => setGuildId(e.target.value)}
            required
            pattern="[0-9]+"
            className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm font-mono focus:outline-none focus:border-indigo-500"
            placeholder="123456789012345678"
          />
        </div>
        <div>
          <label className="text-xs text-gray-400 block mb-1">Voice Channel ID</label>
          <input
            value={channelId}
            onChange={(e) => setChannelId(e.target.value)}
            required
            pattern="[0-9]+"
            className="w-full bg-gray-800 border border-gray-700 rounded-lg px-3 py-2 text-white text-sm font-mono focus:outline-none focus:border-indigo-500"
            placeholder="123456789012345678"
          />
        </div>
        <p className="text-xs text-gray-600">
          A token will be drawn from the pool automatically. Make sure the bot is a member of the server.
        </p>
        {error && <p className="text-red-400 text-xs">{error}</p>}
        <div className="flex gap-3">
          <button
            type="submit"
            disabled={sending}
            className="flex-1 bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 text-white rounded-lg py-2 text-sm font-semibold transition-colors"
          >
            {sending ? "Joining…" : "Join"}
          </button>
          <button
            type="button"
            onClick={onClose}
            className="flex-1 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg py-2 text-sm transition-colors"
          >
            Cancel
          </button>
        </div>
      </form>
    </div>
  );
}

export default function NodeDetailPage() {
  const { id } = useParams<{ id: string }>();
  const router = useRouter();
  const [node, setNode] = useState<NodeRecord | null>(null);
  const [showConfig, setShowConfig] = useState(false);
  const [showDiscordJoin, setShowDiscordJoin] = useState(false);
  const [sending, setSending] = useState(false);
  const [approving, setApproving] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const { systems } = useSystems();
  const { calls } = useCalls(20);
  const { isAdmin } = useAuth();

  const systemMap = Object.fromEntries(systems.map((s) => [s.system_id, s]));
  const nodeCalls = calls.filter((c) => c.node_id === id);

  useEffect(() => {
    const unsub = onSnapshot(doc(db, "nodes", id), (snap) => {
      setNode(snap.exists() ? (snap.data() as NodeRecord) : null);
    });
    return unsub;
  }, [id]);

  async function sendCommand(action: string) {
    setSending(true);
    try {
      await c2api.sendCommand(id, { action });
    } finally {
      setSending(false);
    }
  }

  async function handleApprove() {
    setApproving(true);
    try {
      await c2api.approveNode(id);
    } catch (err) {
      alert(err instanceof Error ? err.message : "Approval failed.");
    } finally {
      setApproving(false);
    }
  }

  async function handleDelete() {
    if (!confirm(`Permanently delete node "${node?.name ?? id}"? This cannot be undone.`)) return;
    setDeleting(true);
    try {
      await c2api.deleteNode(id);
      router.push("/nodes");
    } catch (err) {
      alert(err instanceof Error ? err.message : "Delete failed.");
      setDeleting(false);
    }
  }

  async function handleReject() {
    if (!confirm("Reject this node? It will not be able to upload recordings.")) return;
    setApproving(true);
    try {
      await c2api.rejectNode(id);
    } catch (err) {
      alert(err instanceof Error ? err.message : "Rejection failed.");
    } finally {
      setApproving(false);
    }
  }

  if (!node) {
    return <p className="text-gray-500 font-mono text-sm">Loading node…</p>;
  }

  const system = systemMap[node.assigned_system_id ?? ""];

  return (
    <div className="space-y-6 max-w-3xl">
      <div className="flex items-start justify-between">
        <div>
          <h1 className="text-xl font-bold text-white font-mono">{node.name}</h1>
          <p className="text-gray-500 text-sm font-mono">{node.node_id}</p>
        </div>
        <StatusBadge status={node.status} />
      </div>

      {/* Override Warning */}
      {node.is_overridden && (
        <div className="bg-yellow-950/40 border border-yellow-800/60 rounded-lg p-4 font-mono text-sm space-y-3">
          <div className="flex items-center gap-2 text-yellow-400 font-semibold">
            <span className="text-base">⚠</span>
            <span>Local System Override Active</span>
          </div>
          <p className="text-gray-400 text-xs leading-relaxed">
            This node is operating on a local system override. 
            {node.override_timeout_at ? (
              <> Resets automatically on: <span className="text-white font-bold">{new Date(node.override_timeout_at).toLocaleString()}</span>.</>
            ) : (
              <> No timeout is currently enforced (permanent override).</>
            )}
          </p>
          <div className="flex gap-2">
            {node.override_timeout_at && (
              <button
                onClick={async () => {
                  try {
                    await c2api.ackOverride(id, 1440);
                  } catch (e) {
                    alert("Failed to extend timer.");
                  }
                }}
                className="px-3 py-1 bg-yellow-800 hover:bg-yellow-700 text-white rounded text-xs transition-colors"
              >
                Ack (Reset 24h Timer)
              </button>
            )}
            <button
              onClick={async () => {
                if (confirm("Force this node to revert back to its assigned system config?")) {
                  try {
                    await c2api.resetOverride(id);
                  } catch (e) {
                    alert("Failed to reset override.");
                  }
                }
              }}
              className="px-3 py-1 bg-red-900 hover:bg-red-800 text-red-200 rounded text-xs transition-colors"
            >
              Force Revert Config
            </button>
          </div>
        </div>
      )}

      {/* Info */}
      <div className="bg-gray-900 border border-gray-800 rounded-lg divide-y divide-gray-800 font-mono text-sm">
        {[
          ["System",    system?.name ?? "Unassigned"],
          ["Location",  `${node.lat}, ${node.lon}`],
          ["Last Seen", node.last_seen ? new Date(node.last_seen).toLocaleString() : "never"],
          ["Configured", node.configured ? "Yes" : "No"],
          ["Node Type", node.node_type ?? "fixed"],
          ...(node.node_type !== "portable" ? [["Enforce Timeout", node.enforce_override_timeout ? "Yes" : "No"]] : []),
        ].map(([label, value]) => (
          <div key={label} className="flex justify-between px-4 py-2.5">
            <span className="text-gray-500">{label}</span>
            <span className="text-gray-200">{value}</span>
          </div>
        ))}
        <div className="flex justify-between px-4 py-2.5">
          <span className="text-gray-500">Approval</span>
          <ApprovalBadge status={node.approval_status ?? null} />
        </div>
      </div>

      {/* Admin approval actions */}
      {isAdmin && node.approval_status === "pending" && (
        <div className="flex gap-3 items-center">
          <span className="text-sm text-yellow-400 font-mono">This node is awaiting approval.</span>
          <button
            onClick={handleApprove}
            disabled={approving}
            className="px-4 py-2 bg-green-700 hover:bg-green-600 disabled:opacity-50 text-white rounded-lg text-sm font-mono transition-colors"
          >
            {approving ? "…" : "Approve"}
          </button>
          <button
            onClick={handleReject}
            disabled={approving}
            className="px-4 py-2 bg-red-900 hover:bg-red-800 disabled:opacity-50 text-gray-300 rounded-lg text-sm font-mono transition-colors"
          >
            Reject
          </button>
        </div>
      )}

      {/* Actions */}
      <div className="flex flex-wrap gap-3">
        <button
          onClick={() => setShowConfig(true)}
          className="px-4 py-2 bg-indigo-700 hover:bg-indigo-600 text-white rounded-lg text-sm font-mono transition-colors"
        >
          {node.configured ? "Reassign System" : "Configure"}
        </button>
        <button
          disabled={sending}
          onClick={() => sendCommand("op25_restart")}
          className="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg text-sm font-mono transition-colors disabled:opacity-50"
        >
          Restart OP25
        </button>
        <button
          disabled={sending}
          onClick={() => {
            if (confirm("Restart the node container to apply any pulled image updates?")) {
              sendCommand("node_update");
            }
          }}
          className="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg text-sm font-mono transition-colors disabled:opacity-50"
        >
          Update Node
        </button>
        <button
          onClick={() => setShowDiscordJoin(true)}
          className="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg text-sm font-mono transition-colors"
        >
          Join Discord
        </button>
        <button
          disabled={sending}
          onClick={() => sendCommand("discord_leave")}
          className="px-4 py-2 bg-gray-800 hover:bg-gray-700 text-gray-300 rounded-lg text-sm font-mono transition-colors disabled:opacity-50"
        >
          Leave Discord
        </button>
        {isAdmin && (
          <button
            disabled={deleting}
            onClick={handleDelete}
            className="px-4 py-2 bg-red-900 hover:bg-red-800 disabled:opacity-50 text-red-300 rounded-lg text-sm font-mono transition-colors ml-auto"
          >
            {deleting ? "Deleting…" : "Delete Node"}
          </button>
        )}
      </div>

      {/* Recent calls */}
      <section>
        <h2 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-3">Recent Calls</h2>
        {nodeCalls.length === 0 ? (
          <p className="text-gray-600 text-sm font-mono">No calls recorded from this node.</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="text-xs text-gray-500 uppercase tracking-wider border-b border-gray-800">
                  <th className="px-4 py-2 text-left">Time</th>
                  <th className="px-4 py-2 text-left">Talkgroup</th>
                  <th className="px-4 py-2 text-left">System</th>
                  <th className="px-4 py-2 text-left">Node</th>
                  <th className="px-4 py-2 text-left">Duration</th>
                  <th className="px-4 py-2 text-left">Audio</th>
                </tr>
              </thead>
              <tbody>
                {nodeCalls.map((c) => (
                  <CallRow key={c.call_id} call={c} systemName={system?.name} />
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      {showConfig && (
        <NodeConfigModal
          node={node}
          systems={systems}
          onClose={() => setShowConfig(false)}
        />
      )}

      {showDiscordJoin && (
        <DiscordJoinModal
          nodeId={id}
          onClose={() => setShowDiscordJoin(false)}
        />
      )}
    </div>
  );
}
