"use client";

import { useEffect, useState, useCallback } from "react";
import Link from "next/link";
import { api } from "@/lib/api";
import { getSocket } from "@/lib/socket";
import type { Negotiation, Stats } from "@/lib/types";
import {
  FEATURE_LABELS,
  STATUS_COLORS,
  STATUS_LABELS,
  relativeTime,
} from "@/lib/utils";
import Sidebar from "@/components/Sidebar";

// ─── Icon helper ─────────────────────────────────────────────────────────────
function Icon({ name, className = "" }: { name: string; className?: string }) {
  return (
    <span className={`material-symbols-outlined ${className}`}>{name}</span>
  );
}

// ─── Feature icon map ─────────────────────────────────────────────────────────
const FEATURE_ICONS: Record<string, string> = {
  scheduling: "calendar_month",
  expenses: "account_balance_wallet",
  freelance: "work",
  roommate: "home",
  trip: "flight_takeoff",
  marketplace: "store",
  collaborative: "groups",
  conflict: "gavel",
  generic: "hub",
};

export default function DashboardPage() {
  const [stats, setStats] = useState<Stats | null>(null);
  const [negotiations, setNegotiations] = useState<Negotiation[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [connected, setConnected] = useState(false);
  const [search, setSearch] = useState("");

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const [s, n] = await Promise.all([api.stats(), api.negotiations()]);
      setStats(s);
      setNegotiations(n.negotiations);
      setError(null);
    } catch (e) {
      setError(String(e));
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    load();
    const socket = getSocket();
    const onConnect = () => setConnected(true);
    const onDisconnect = () => setConnected(false);
    const onUpdate = () => load();
    socket.on("connect", onConnect);
    socket.on("disconnect", onDisconnect);
    socket.on("negotiation_started", onUpdate);
    socket.on("negotiation_resolved", onUpdate);
    setConnected(socket.connected);
    return () => {
      socket.off("connect", onConnect);
      socket.off("disconnect", onDisconnect);
      socket.off("negotiation_started", onUpdate);
      socket.off("negotiation_resolved", onUpdate);
    };
  }, [load]);

  const successRate = stats
    ? Math.round((stats.resolved / Math.max(stats.total_negotiations, 1)) * 100)
    : 0;

  const filteredNegotiations = search.trim()
    ? negotiations.filter((n) =>
        n.id.toLowerCase().includes(search.toLowerCase()) ||
        n.feature_type?.toLowerCase().includes(search.toLowerCase()) ||
        n.status?.toLowerCase().includes(search.toLowerCase())
      )
    : negotiations;

  return (
    <div className="flex h-screen w-full overflow-hidden bg-[#020105] text-slate-300 relative">
      {/* Grid overlay */}
      <div className="absolute inset-0 bg-grid-subtle opacity-20 pointer-events-none" />

      {/* ── Sidebar ── */}
      <Sidebar />

      {/* ── Main ── */}
      <main className="flex-1 flex flex-col h-full overflow-hidden relative z-10">
        {/* Top bar */}
        <header className="h-14 flex items-center justify-between px-6 bg-[#020105]/90 backdrop-blur-md border-b border-white/[0.06] sticky top-0 z-30 shrink-0">
          <div className="flex items-center gap-3">
            <h2 className="text-sm font-semibold text-white tracking-tight">
              Mission Control
            </h2>
            <span className="px-2 py-0.5 rounded-full bg-[#B7A6FB]/10 border border-[#B7A6FB]/20 text-[9px] text-[#B7A6FB] font-mono tracking-widest uppercase">
              Live
            </span>
          </div>

          <div className="flex items-center gap-2">
            {/* Search */}
            <div className="relative hidden md:block group">
              <Icon name="search" className="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-600 group-focus-within:text-[#B7A6FB] transition-colors text-base" />
              <input
                className="h-8 w-52 bg-white/[0.04] border border-white/[0.08] rounded-lg pl-8 pr-3 text-xs text-white placeholder-slate-600 focus:outline-none focus:border-[#B7A6FB]/30 transition-all"
                placeholder="Search negotiations..."
                type="text"
                value={search}
                onChange={(e) => setSearch(e.target.value)}
              />
            </div>
            {/* Refresh */}
            <button
              onClick={load}
              disabled={loading}
              className="h-8 w-8 flex items-center justify-center rounded-lg bg-white/[0.04] border border-white/[0.08] text-slate-500 hover:text-white hover:border-white/20 transition-all disabled:opacity-30"
              title="Refresh"
            >
              <Icon name="refresh" className={`text-base ${loading ? "animate-spin" : ""}`} />
            </button>
            {/* Connection badge */}
            <div
              className={`flex items-center gap-1.5 h-8 px-3 rounded-lg border font-mono text-[10px] ${
                connected
                  ? "bg-emerald-500/10 text-emerald-400 border-emerald-500/20"
                  : "bg-white/[0.04] text-slate-500 border-white/[0.08]"
              }`}
            >
              <span className={`size-1.5 rounded-full ${connected ? "bg-emerald-400 animate-pulse" : "bg-slate-600"}`} />
              {connected ? "Connected" : "Offline"}
            </div>
            {/* Profile avatar */}
            <Link
              href="/profile"
              className="size-8 rounded-full bg-gradient-to-br from-[#B7A6FB]/30 to-[#22d3ee]/20 border border-[#B7A6FB]/40 flex items-center justify-center text-white text-[11px] font-black hover:border-[#B7A6FB] hover:shadow-[0_0_12px_rgba(183,166,251,0.3)] transition-all"
              title="View Profile"
            >
              AB
            </Link>
          </div>
        </header>

        {/* Scrollable content */}
        <div className="flex-1 overflow-y-auto p-6 scroll-smooth">
          {/* Error */}
          {error && (
            <div className="mb-5 p-4 bg-red-500/10 border border-red-500/20 rounded-xl text-xs text-red-400 flex items-center gap-2">
              <Icon name="error" className="text-base shrink-0" />
              {error} —{" "}
              <button onClick={load} className="underline hover:text-red-300">
                retry
              </button>
            </div>
          )}

          {/* ── Stat cards ── */}
          <section className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-7">
            <StatCard
              icon="hub"
              label="Active Links"
              value={stats?.active ?? "—"}
              sub={`${stats?.total_negotiations ?? 0} total`}
              bars={[40, 60, 30, 80, 50]}
              activeBar={3}
              accent="#B7A6FB"
            />
            <StatCard
              icon="check_circle"
              label="Resolved"
              value={stats?.resolved ?? "—"}
              sub={`${successRate}% success rate`}
              bars={[60, 50, 90, 40, 70]}
              activeBar={2}
              accent="#34d399"
            />
            <StatCard
              icon="group"
              label="Users"
              value={stats?.total_users ?? "—"}
              sub="registered agents"
              bars={[30, 70, 50, 90, 60]}
              activeBar={3}
              accent="#60a5fa"
            />
            <StatCard
              icon="balance"
              label="Avg Fairness"
              value={stats ? `${stats.avg_fairness_score}` : "—"}
              sub="fairness index"
              bars={[50, 65, 70, 75, 80]}
              activeBar={4}
              accent="#f59e0b"
            />
          </section>

          {/* ── Feature breakdown ── */}
          {stats?.feature_breakdown && stats.feature_breakdown.length > 0 && (
            <section className="glass-card rounded-xl p-5 mb-7">
              <div className="flex items-center gap-2 mb-4">
                <h3 className="text-xs font-semibold text-slate-400 uppercase tracking-widest">Protocol Distribution</h3>
              </div>
              <div className="flex flex-wrap gap-2">
                {stats.feature_breakdown.map((fb) => (
                  <span
                    key={fb.feature_type}
                    className="flex items-center gap-1.5 text-[10px] px-3 py-1.5 bg-white/5 text-slate-300 border border-white/10 rounded-full font-mono hover:border-[#B7A6FB]/30 transition-colors"
                  >
                    <Icon name={FEATURE_ICONS[fb.feature_type] ?? "hub"} className="text-sm text-[#B7A6FB]" />
                    {FEATURE_LABELS[fb.feature_type]} · <span className="text-[#B7A6FB]">{fb.c}</span>
                  </span>
                ))}
              </div>
            </section>
          )}

          {/* ── Active Cycles ── */}
          <section>
            <div className="flex items-center justify-between mb-5">
              <div className="flex items-center gap-2.5">
                <h3 className="text-sm font-semibold text-white tracking-wide">
                  Active Cycles
                </h3>
                {stats?.active != null && stats.active > 0 && (
                  <span className="text-[9px] px-2 py-0.5 bg-red-500/10 border border-red-500/20 rounded-full text-red-400 font-mono animate-pulse tracking-wide">
                    {stats.active} LIVE
                  </span>
                )}
              </div>
              <div className="flex items-center gap-2">
                <button className="h-8 flex items-center gap-1.5 px-3 text-[11px] font-semibold text-[#B7A6FB] bg-[#B7A6FB]/10 border border-[#B7A6FB]/25 rounded-lg hover:bg-[#B7A6FB]/20 transition-all tracking-wide">
                  <Icon name="add" className="text-base" />
                  Initialize
                </button>
                <button className="h-8 w-8 flex items-center justify-center text-slate-500 bg-white/[0.04] border border-white/[0.08] rounded-lg hover:text-white hover:border-white/20 transition-all">
                  <Icon name="filter_list" className="text-base" />
                </button>
              </div>
            </div>

            {loading ? (
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
                {[1, 2, 3].map((i) => (
                  <div key={i} className="glass-card rounded-xl h-52 animate-pulse" />
                ))}
              </div>
            ) : filteredNegotiations.length === 0 ? (
              <div className="glass-card rounded-xl py-20 text-center">
                <Icon name={search ? "search_off" : "hub"} className="text-5xl text-slate-700 block mx-auto mb-3" />
                <p className="text-sm text-slate-500">{search ? `No results for "${search}"` : "No negotiations yet."}</p>
                <p className="text-[10px] text-slate-700 mt-1 font-mono">{search ? "Try a different keyword." : "Start one via Telegram bot!"}</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5">
                {filteredNegotiations.map((neg) => (
                  <NegotiationCard key={neg.id} neg={neg} />
                ))}
              </div>
            )}
          </section>

          <div className="mt-10 text-center text-[9px] text-slate-700 pb-4 font-mono">
            // SYSTEM_ID: AM-2024 // STATUS:{" "}
            <span className="text-emerald-500">OPERATIONAL</span> // LATENCY: 12ms
          </div>
        </div>
      </main>
    </div>
  );
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function StatCard({
  icon,
  label,
  value,
  sub,
  bars,
  activeBar,
  accent = "#B7A6FB",
}: {
  icon: string;
  label: string;
  value: number | string;
  sub: string;
  bars: number[];
  activeBar: number;
  accent?: string;
}) {
  return (
    <div
      className="rounded-xl p-5 flex flex-col justify-between group hover:-translate-y-0.5 transition-transform duration-300 relative overflow-hidden"
      style={{
        background: "rgba(7,3,18,0.55)",
        border: "1px solid rgba(255,255,255,0.07)",
        boxShadow: "0 4px 24px rgba(0,0,0,0.45)",
      }}
    >
      {/* Subtle top accent line */}
      <div
        className="absolute top-0 left-0 right-0 h-[2px] rounded-t-xl opacity-60"
        style={{ background: `linear-gradient(to right, ${accent}, transparent)` }}
      />

      {/* Top row: label + icon */}
      <div className="flex items-center justify-between mb-3">
        <span className="text-[10px] font-semibold uppercase tracking-widest text-slate-500">
          {label}
        </span>
        <div
          className="size-8 rounded-lg flex items-center justify-center shrink-0"
          style={{ background: `${accent}18`, border: `1px solid ${accent}30` }}
        >
          <span className="material-symbols-outlined text-[17px]" style={{ color: accent }}>
            {icon}
          </span>
        </div>
      </div>

      {/* Value */}
      <div className="mb-3">
        <span
          className="text-[2.15rem] font-light leading-none tracking-tight"
          style={{ color: "rgba(255,255,255,0.92)" }}
        >
          {value}
        </span>
      </div>

      {/* Bottom row: mini bars + sub-label */}
      <div className="flex items-end justify-between gap-2">
        <div className="flex items-end gap-[3px] h-5">
          {bars.map((h, i) => (
            <div
              key={i}
              className="w-[3px] rounded-sm transition-all duration-300"
              style={{
                height: `${h}%`,
                background: i === activeBar ? accent : `${accent}35`,
                boxShadow: i === activeBar ? `0 0 6px ${accent}` : "none",
              }}
            />
          ))}
        </div>
        <span className="text-[10px] font-mono text-slate-600 truncate">{sub}</span>
      </div>
    </div>
  );
}

function NegotiationCard({ neg }: { neg: Negotiation }) {
  const isLive = neg.status === "active";
  const isPaused = neg.status === "pending";

  const statusDot: Record<string, string> = {
    active: "bg-red-500 animate-pulse",
    resolved: "bg-emerald-500",
    pending: "bg-slate-500",
    escalated: "bg-amber-500",
  };

  const statusLabel: Record<string, string> = {
    active: "Live",
    resolved: "Sync",
    pending: "Pending",
    escalated: "Escalated",
  };

  const statusColor: Record<string, string> = {
    active: "text-red-400 bg-red-500/10 border-red-500/20",
    resolved: "text-emerald-400 bg-emerald-500/10 border-emerald-500/20",
    pending: "text-slate-400 bg-white/5 border-white/10",
    escalated: "text-amber-400 bg-amber-500/10 border-amber-500/20",
  };

  return (
    <div className="glass-card rounded-xl overflow-hidden hover:scale-[1.01] transition-all duration-300 group relative">
      <div className="p-5 relative">
        {/* Header */}
        <div className="flex justify-between items-start mb-5">
          <div className="flex items-center gap-3">
            <div className="size-10 rounded-lg bg-white/5 border border-white/10 flex items-center justify-center">
              <Icon name={FEATURE_ICONS[neg.feature_type] ?? "hub"} className="text-[#B7A6FB]" />
            </div>
            <div>
              <h4 className="text-sm font-medium text-white truncate max-w-[140px]">
                {FEATURE_LABELS[neg.feature_type]}
              </h4>
              <span className="text-[9px] font-mono text-slate-600">ID: #{neg.id.slice(0, 8)}</span>
            </div>
          </div>
          <div className={`flex items-center gap-1.5 px-2 py-1 border rounded text-[9px] font-bold uppercase tracking-wide ${statusColor[neg.status]}`}>
            <div className={`size-1.5 rounded-full ${statusDot[neg.status]}`} />
            {statusLabel[neg.status]}
          </div>
        </div>

        {/* Details */}
        <div className="space-y-2.5 mb-5">
          <div className="flex justify-between items-center text-xs border-b border-white/5 pb-2">
            <span className="text-slate-500 font-mono">participants</span>
            <span className="text-slate-300 font-mono">{neg.participant_count ?? 0} agents</span>
          </div>
          <div className="flex justify-between items-center text-xs border-b border-white/5 pb-2">
            <span className="text-slate-500 font-mono">status</span>
            <span className={`font-mono text-[10px] px-1.5 py-0.5 rounded border ${STATUS_COLORS[neg.status] ?? "text-slate-400 border-white/10"}`}>
              {STATUS_LABELS[neg.status] ?? neg.status}
            </span>
          </div>
          <div className="flex justify-between items-center text-xs">
            <span className="text-slate-500 font-mono">initiated</span>
            <span className="text-slate-400 font-mono bg-white/5 px-1.5 rounded border border-white/10 text-[10px]">
              {relativeTime(neg.created_at)}
            </span>
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between pt-4 border-t border-white/5">
          <div className="flex -space-x-2">
            {[...Array(Math.min(neg.participant_count ?? 0, 2))].map((_, i) => (
              <div
                key={i}
                className="w-6 h-6 rounded-full bg-slate-800 border border-black flex items-center justify-center text-[8px] text-white ring-1 ring-white/10"
              >
                {String.fromCharCode(65 + i)}
              </div>
            ))}
            <div className="w-6 h-6 rounded-full border border-black bg-[#B7A6FB]/20 flex items-center justify-center text-[7px] text-[#B7A6FB] ring-1 ring-white/10">
              AI
            </div>
          </div>
          <Link
            href={`/negotiation/${neg.id}`}
            className="text-[#B7A6FB] hover:text-white text-[10px] font-medium flex items-center gap-1 transition-colors group/btn uppercase tracking-wider"
          >
            <span>{isPaused ? "Resume" : isLive ? "Access Stream" : "View Report"}</span>
            <Icon name="arrow_forward" className="text-sm group-hover/btn:translate-x-0.5 transition-transform" />
          </Link>
        </div>
      </div>

      {/* Corner plus */}
      <div className="absolute bottom-4 right-4 opacity-0 group-hover:opacity-100 transition-opacity">
        <div className="w-5 h-5 rounded-full bg-white/5 border border-white/10 flex items-center justify-center text-[#B7A6FB]">
          <Icon name="add" className="text-xs" />
        </div>
      </div>
    </div>
  );
}

