"use client";

import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";

interface AlertSub {
  id: string;
  kind: string;
  params: Record<string, unknown>;
  enabled: boolean;
  createdAt: string;
}

const KIND_INFO: Record<
  string,
  { label: string; desc: string; icon: string; params: Array<{ key: string; label: string; placeholder: string; type: "number" | "text" }> }
> = {
  liquidation: {
    label: "Liquidation Alerter",
    desc: "Alerts when positions are liquidated above threshold.",
    icon: "🔥",
    params: [
      { key: "minUsd", label: "Min size USD", placeholder: "100000", type: "number" },
      { key: "asset", label: "Asset (optional)", placeholder: "BTC, ETH, or empty for all", type: "text" },
    ],
  },
  whale: {
    label: "Whale Spike",
    desc: "Single trades above threshold (any direction).",
    icon: "🐋",
    params: [
      { key: "minUsd", label: "Min size USD", placeholder: "250000", type: "number" },
      { key: "asset", label: "Asset (optional)", placeholder: "BTC", type: "text" },
    ],
  },
  smart_money: {
    label: "Smart-Money Copy",
    desc: "Curated top traders' wallet movements.",
    icon: "🧠",
    params: [
      { key: "minUsd", label: "Min size USD", placeholder: "50000", type: "number" },
    ],
  },
  token_unlock: {
    label: "Token Unlock Calendar",
    desc: "Coming next: 7-day-ahead unlocks.",
    icon: "🔓",
    params: [
      { key: "tokens", label: "Tokens (comma-separated)", placeholder: "ARB,OP,APT", type: "text" },
    ],
  },
};

const TIER_LIMITS: Record<string, number> = { free: 1, pro: 10, plus: 50 };

export function AlertsManager({ initial, tier }: { initial: AlertSub[]; tier: string }) {
  const router = useRouter();
  const [alerts, setAlerts] = useState<AlertSub[]>(initial);
  const [showAdd, setShowAdd] = useState(false);
  const [, startTransition] = useTransition();
  const limit = TIER_LIMITS[tier] ?? 1;

  async function createAlert(kind: string, params: Record<string, unknown>) {
    const res = await fetch("/api/proxy/alerts", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ kind, params }),
    });
    if (res.ok) {
      const sub = await res.json();
      setAlerts((a) => [sub, ...a]);
      setShowAdd(false);
      startTransition(() => router.refresh());
    } else {
      const err = await res.json().catch(() => ({}));
      alert(err?.error === "tier_limit_reached" ? `Tier limit reached (${limit}). Upgrade for more.` : "Failed to create alert");
    }
  }

  async function toggleAlert(id: string, enabled: boolean) {
    const res = await fetch(`/api/proxy/alerts/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ enabled }),
    });
    if (res.ok) {
      setAlerts((a) => a.map((x) => (x.id === id ? { ...x, enabled } : x)));
    }
  }

  async function deleteAlert(id: string) {
    if (!confirm("Delete this alert?")) return;
    const res = await fetch(`/api/proxy/alerts/${id}`, { method: "DELETE" });
    if (res.ok) {
      setAlerts((a) => a.filter((x) => x.id !== id));
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <span className="text-sm text-white/50 font-mono">
          {alerts.length}/{limit} configured
        </span>
        <button
          onClick={() => setShowAdd(true)}
          disabled={alerts.length >= limit}
          className="bg-accent-500 hover:bg-accent-400 disabled:opacity-40 text-ink-950 font-semibold px-4 py-2 rounded-lg text-sm"
        >
          + Add alert
        </button>
      </div>

      {alerts.length === 0 ? (
        <div className="bg-ink-800/50 border border-white/10 rounded-xl p-8 text-center">
          <div className="text-4xl mb-3">🔔</div>
          <p className="text-white/60 mb-4">No alerts yet.</p>
          <button
            onClick={() => setShowAdd(true)}
            className="bg-accent-500 hover:bg-accent-400 text-ink-950 font-semibold px-5 py-2.5 rounded-lg"
          >
            Add your first alert
          </button>
        </div>
      ) : (
        <div className="space-y-2">
          {alerts.map((a) => {
            const info = KIND_INFO[a.kind];
            return (
              <div key={a.id} className="bg-ink-800/50 border border-white/10 rounded-lg p-4 flex items-center gap-4">
                <span className="text-2xl">{info?.icon ?? "•"}</span>
                <div className="flex-1 min-w-0">
                  <div className="font-semibold">{info?.label ?? a.kind}</div>
                  <div className="text-xs text-white/40 font-mono truncate">
                    {Object.entries(a.params)
                      .map(([k, v]) => `${k}=${v}`)
                      .join(" · ") || "default params"}
                  </div>
                </div>
                <button
                  onClick={() => toggleAlert(a.id, !a.enabled)}
                  className={`px-3 py-1 rounded text-xs font-mono ${
                    a.enabled ? "bg-emerald-500/20 text-emerald-400" : "bg-white/5 text-white/40"
                  }`}
                >
                  {a.enabled ? "ON" : "OFF"}
                </button>
                <button
                  onClick={() => deleteAlert(a.id)}
                  className="text-white/30 hover:text-red-400 transition px-2"
                  aria-label="Delete"
                >
                  ✕
                </button>
              </div>
            );
          })}
        </div>
      )}

      {showAdd && <AddAlertModal onClose={() => setShowAdd(false)} onCreate={createAlert} />}
    </div>
  );
}

function AddAlertModal({
  onClose,
  onCreate,
}: {
  onClose: () => void;
  onCreate: (kind: string, params: Record<string, unknown>) => void;
}) {
  const [kind, setKind] = useState<string>("liquidation");
  const [params, setParams] = useState<Record<string, string>>({});
  const info = KIND_INFO[kind];

  function submit() {
    const cast: Record<string, unknown> = {};
    for (const p of info.params) {
      const v = params[p.key];
      if (!v) continue;
      cast[p.key] = p.type === "number" ? Number(v) : v;
    }
    onCreate(kind, cast);
  }

  return (
    <div className="fixed inset-0 z-50 bg-black/70 backdrop-blur grid place-items-center px-6" onClick={onClose}>
      <div className="bg-ink-900 border border-white/10 rounded-2xl p-6 max-w-md w-full" onClick={(e) => e.stopPropagation()}>
        <h2 className="text-xl font-bold mb-1">New alert</h2>
        <p className="text-sm text-white/50 mb-4">Pick a type and set thresholds.</p>

        <div className="grid grid-cols-2 gap-2 mb-4">
          {Object.entries(KIND_INFO).map(([k, info]) => (
            <button
              key={k}
              onClick={() => {
                setKind(k);
                setParams({});
              }}
              className={`text-left p-3 rounded-lg border transition ${
                kind === k ? "border-accent-500/50 bg-accent-500/10" : "border-white/10 bg-ink-800/30 hover:border-white/20"
              }`}
            >
              <div className="text-xl mb-1">{info.icon}</div>
              <div className="text-sm font-semibold">{info.label}</div>
            </button>
          ))}
        </div>

        <p className="text-xs text-white/50 mb-3">{info.desc}</p>

        <div className="space-y-3 mb-6">
          {info.params.map((p) => (
            <div key={p.key}>
              <label className="block text-xs uppercase tracking-wider text-white/50 mb-1">{p.label}</label>
              <input
                type={p.type === "number" ? "number" : "text"}
                placeholder={p.placeholder}
                value={params[p.key] ?? ""}
                onChange={(e) => setParams((s) => ({ ...s, [p.key]: e.target.value }))}
                className="w-full px-3 py-2 bg-ink-800 border border-white/10 rounded-lg text-sm focus:border-accent-500 focus:outline-none"
              />
            </div>
          ))}
        </div>

        <div className="flex gap-2">
          <button onClick={onClose} className="flex-1 py-2.5 rounded-lg bg-ink-700 hover:bg-ink-600 text-white font-semibold text-sm">
            Cancel
          </button>
          <button onClick={submit} className="flex-1 py-2.5 rounded-lg bg-accent-500 hover:bg-accent-400 text-ink-950 font-bold text-sm">
            Create
          </button>
        </div>
      </div>
    </div>
  );
}
