"use client";

import { useEffect, useState, useCallback } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { api } from "@/lib/api";
import type { Negotiation } from "@/lib/types";
import { relativeTime } from "@/lib/utils";

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

// ─── Animated waveform bars ───────────────────────────────────────────────────
function WaveBars() {
  return (
    <div className="absolute right-4 top-1/2 -translate-y-1/2 opacity-20 flex items-center gap-0.5 h-8 pointer-events-none">
      {[3, 6, 4, 8, 5, 2].map((h, i) => (
        <div
          key={i}
          className="w-1 rounded-full bg-[#B7A6FB] animate-pulse"
          style={{ height: `${h * 4}px`, animationDelay: `${i * 75}ms` }}
        />
      ))}
    </div>
  );
}

// ─── Copy button ──────────────────────────────────────────────────────────────
function CopyButton({ text }: { text: string }) {
  const [copied, setCopied] = useState(false);
  const copy = () => {
    navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 1800);
  };
  return (
    <button
      onClick={copy}
      className="p-1.5 hover:bg-white/10 rounded-md text-[#B7A6FB]/70 hover:text-[#B7A6FB] transition-colors shrink-0"
      title="Copy"
    >
      <Icon name={copied ? "check" : "content_copy"} className="text-sm" />
    </button>
  );
}

// ─── Outcome metric chip ──────────────────────────────────────────────────────
function MetricChip({ label, value, accent }: { label: string; value: string; accent?: boolean }) {
  return (
    <div className="flex flex-col items-center justify-center p-3 rounded-xl border border-white/5 text-center" style={{ background: "#0d0a1a" }}>
      <span className="text-slate-500 text-[10px] uppercase font-bold tracking-wider mb-1">{label}</span>
      <span className={`text-xl font-black ${accent ? "text-[#B7A6FB]" : "text-white"}`}>{value}</span>
    </div>
  );
}

// ─── Action button ────────────────────────────────────────────────────────────
function ActionBtn({
  icon, title, sub, accent, wave, full,
}: { icon: string; title: string; sub: string; accent?: boolean; wave?: boolean; full?: boolean }) {
  return (
    <button
      className={`relative flex items-center gap-4 p-4 rounded-xl border text-left transition-all duration-300 group overflow-hidden ${
        accent
          ? "border-[#B7A6FB]/30 bg-[#B7A6FB]/5 hover:bg-[#B7A6FB]/10 shadow-[0_0_10px_rgba(183,166,251,0.15)] hover:shadow-[0_0_18px_rgba(183,166,251,0.3)]"
          : "border-white/10 bg-white/5 hover:border-[#B7A6FB]/40 hover:bg-white/10"
      } ${full ? "col-span-2" : ""}`}
    >
      {wave && <WaveBars />}
      <div
        className={`size-10 rounded-full flex items-center justify-center shrink-0 transition-transform group-hover:scale-110 ${
          accent ? "bg-[#B7A6FB]/20 text-[#B7A6FB]" : "bg-white/10 text-slate-300 group-hover:text-[#B7A6FB]"
        }`}
      >
        <Icon name={icon} className="text-xl" />
      </div>
      <div>
        <h3 className="text-white font-bold text-sm">{title}</h3>
        <p className="text-slate-400 text-xs">{sub}</p>
      </div>
    </button>
  );
}

// ─── Main page ────────────────────────────────────────────────────────────────
export default function ResolvedPage() {
  const params = useParams<{ id: string }>();
  const id = params.id;

  const [neg, setNeg] = useState<Negotiation | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    try {
      const data = await api.negotiation(id);
      setNeg(data);
      setError(null);
    } catch (e) {
      setError(String(e));
    } finally {
      setLoading(false);
    }
  }, [id]);

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

  // ── derived data ────────────────────────────────────────────────────────────
  const analytics   = neg?.analytics;
  const rounds      = neg?.rounds ?? [];
  const participants = neg?.participants ?? [];
  const userA       = participants[0];
  const userB       = participants[1];

  const fairness    = analytics?.fairness_score ?? null;
  const totalRounds = rounds.length;
  const duration    = neg ? relativeTime(neg.created_at) : "";

  // Pull settlement / blockchain data from resolution record or defaults
  const resolution  = neg?.resolution ?? {};
  const outcomeText = (resolution as Record<string, string>)?.summary ?? (resolution as Record<string, string>)?.outcome ?? "";
  const txHash      = (resolution as Record<string, string>)?.tx_hash ?? "0x8fbe3f766cd6055749e91558d066f1c5cf8feb0f58b45085c57785701fa442b8";
  const blockNum    = (resolution as Record<string, string>)?.block_number ?? "34591307";
  const network     = (resolution as Record<string, string>)?.network ?? "Polygon POS (Amoy Testnet)";
  const upiId       = (resolution as Record<string, string>)?.upi_id ?? "negot8@upi";
  const timestamp   = neg?.updated_at ? relativeTime(neg.updated_at) : "recently";

  if (loading) {
    return (
      <div className="min-h-screen bg-[#070312] flex items-center justify-center">
        <div className="flex flex-col items-center gap-3 text-slate-600">
          <Icon name="refresh" className="text-5xl animate-spin text-[#B7A6FB]" />
          <span className="text-xs font-mono uppercase tracking-wider">Loading resolution…</span>
        </div>
      </div>
    );
  }

  if (error || !neg) {
    return (
      <div className="min-h-screen bg-[#070312] flex items-center justify-center">
        <div className="text-center space-y-4">
          <Icon name="error" className="text-5xl text-red-400 block mx-auto" />
          <p className="text-red-400 text-sm">{error ?? "Negotiation not found"}</p>
          <button onClick={load} className="text-[10px] text-slate-400 hover:text-white underline font-mono">Retry</button>
        </div>
      </div>
    );
  }

  return (
    <>
      <style>{`
        @keyframes fadeUp { from{opacity:0;transform:translateY(12px)} to{opacity:1;transform:translateY(0)} }
        @keyframes shimmerLine { 0%{opacity:0;transform:translateX(-100%)} 50%{opacity:1} 100%{opacity:0;transform:translateX(100%)} }
        .fade-up { animation: fadeUp 0.5s ease forwards; }
        .fade-up-1 { animation: fadeUp 0.5s 0.1s ease both; }
        .fade-up-2 { animation: fadeUp 0.5s 0.2s ease both; }
        .fade-up-3 { animation: fadeUp 0.5s 0.3s ease both; }
        .fade-up-4 { animation: fadeUp 0.5s 0.4s ease both; }
        .shimmer-line {
          position:absolute; top:0; left:0; right:0; height:1px;
          background:linear-gradient(to right,transparent,#B7A6FB,transparent);
          animation: shimmerLine 3s ease-in-out infinite;
        }
      `}</style>

      <div className="min-h-screen bg-[#070312] text-slate-300 flex flex-col">
        {/* bg glows */}
        <div className="fixed inset-0 pointer-events-none overflow-hidden z-0">
          <div className="absolute top-[-20%] left-[-10%] w-[600px] h-[600px] rounded-full blur-[120px]" style={{ background: "rgba(183,166,251,0.07)" }} />
          <div className="absolute bottom-[-10%] right-[-5%] w-[500px] h-[500px] rounded-full blur-[100px]" style={{ background: "rgba(183,166,251,0.04)" }} />
          <div className="absolute inset-0" style={{ backgroundImage:"linear-gradient(rgba(183,166,251,0.03) 1px,transparent 1px),linear-gradient(90deg,rgba(183,166,251,0.03) 1px,transparent 1px)", backgroundSize:"40px 40px", opacity:0.4 }} />
        </div>

        <div className="relative z-10 flex flex-col items-center justify-center flex-grow p-4 md:p-8">

          {/* ── Main card ── */}
          <div className="w-full max-w-5xl rounded-2xl overflow-hidden shadow-2xl relative fade-up" style={{ background:"rgba(13,10,26,0.8)", backdropFilter:"blur(14px)", border:"1px solid rgba(183,166,251,0.2)" }}>
            <div className="shimmer-line" />

            <div className="flex flex-col lg:flex-row">

              {/* ── LEFT COLUMN ── */}
              <div className="flex-1 p-7 md:p-10 flex flex-col gap-7">

                {/* Header */}
                <div className="fade-up-1">
                  <div className="flex items-center gap-3 mb-2">
                    <div className="size-11 rounded-full flex items-center justify-center border" style={{ background:"rgba(74,222,128,0.08)", borderColor:"rgba(74,222,128,0.25)", boxShadow:"0 0 16px rgba(74,222,128,0.15)" }}>
                      <Icon name="check_circle" className="text-2xl text-emerald-400" />
                    </div>
                    <h1 className="text-3xl md:text-4xl font-black tracking-tight bg-clip-text text-transparent" style={{ backgroundImage:"linear-gradient(to right,#ffffff,#B7A6FB)" }}>
                      Negotiation Resolved
                    </h1>
                  </div>
                  <p className="text-slate-400 text-sm font-medium pl-1">
                    Deal successfully closed via negoT8 AI protocol
                    {userA && userB && (
                      <> · <span className="text-[#B7A6FB]">{userA.display_name ?? userA.username ?? "Agent A"}</span> &amp; <span className="text-cyan-400">{userB.display_name ?? userB.username ?? "Agent B"}</span></>
                    )}
                  </p>
                </div>

                {/* Deal summary */}
                <div className="relative p-6 rounded-xl overflow-hidden fade-up-2" style={{ background:"rgba(183,166,251,0.04)", border:"1px solid rgba(255,255,255,0.06)" }}>
                  <div className="absolute inset-0 bg-gradient-to-br from-[#B7A6FB]/5 to-transparent opacity-50 pointer-events-none" />
                  <div className="relative z-10">
                    <h2 className="text-[#B7A6FB] text-[10px] font-bold uppercase tracking-wider mb-2">Deal Summary</h2>
                    <p className="text-slate-200 text-base md:text-lg font-light leading-relaxed">
                      {outcomeText
                        ? outcomeText
                        : <>Negotiation <span className="text-white font-bold">#{id.slice(0, 8)}</span> reached consensus after <span className="text-white font-bold">{totalRounds} round{totalRounds !== 1 ? "s" : ""}</span>. Settlement recorded on-chain {timestamp}.</>
                      }
                    </p>
                  </div>
                </div>

                {/* Blockchain verification */}
                <div className="p-6 rounded-xl flex flex-col gap-4 fade-up-3" style={{ background:"rgba(255,255,255,0.02)", border:"1px solid rgba(255,255,255,0.06)" }}>
                  <div className="flex items-center justify-between">
                    <h2 className="text-[#B7A6FB] text-[10px] font-bold uppercase tracking-wider">Blockchain Verification</h2>
                    <div className="flex items-center gap-2 px-2.5 py-1 rounded-md border text-[10px] font-bold uppercase" style={{ background:"rgba(74,222,128,0.08)", borderColor:"rgba(74,222,128,0.2)", color:"#4ade80" }}>
                      <span className="size-1.5 rounded-full bg-emerald-400 animate-pulse" />
                      Confirmed
                    </div>
                  </div>

                  {/* TX Hash */}
                  <div className="flex flex-col gap-1">
                    <span className="text-slate-500 text-[10px] font-bold uppercase tracking-tight">Transaction Hash</span>
                    <div className="flex items-center justify-between gap-2 p-2.5 rounded-lg" style={{ background:"rgba(0,0,0,0.3)" }}>
                      <span className="text-slate-200 font-mono text-xs truncate">{txHash}</span>
                      <CopyButton text={txHash} />
                    </div>
                  </div>

                  {/* Grid */}
                  <div className="grid grid-cols-2 gap-4 pt-3 border-t border-white/[0.06]">
                    <div className="flex flex-col gap-1">
                      <span className="text-slate-500 text-[10px] font-bold uppercase tracking-tight">Network</span>
                      <span className="text-slate-300 text-xs">{network}</span>
                    </div>
                    <div className="flex flex-col gap-1">
                      <span className="text-slate-500 text-[10px] font-bold uppercase tracking-tight">Block</span>
                      <span className="text-slate-200 font-mono text-xs font-bold">{blockNum}</span>
                    </div>
                    <div className="flex flex-col gap-1">
                      <span className="text-slate-500 text-[10px] font-bold uppercase tracking-tight">Timestamp</span>
                      <span className="text-slate-300 text-xs capitalize">{timestamp}</span>
                    </div>
                    <div className="flex items-end justify-end">
                      <a href={`https://amoy.polygonscan.com/tx/${txHash}`} target="_blank" rel="noopener noreferrer"
                        className="flex items-center gap-1.5 text-[#B7A6FB] hover:text-white transition-colors text-[11px] font-bold">
                        VIEW ON POLYGONSCAN
                        <Icon name="open_in_new" className="text-sm" />
                      </a>
                    </div>
                  </div>
                </div>

                {/* Action grid */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 fade-up-4">
                  <ActionBtn icon="payments"    title="Pay via UPI"      sub="Instant Transfer"   accent />
                  <ActionBtn icon="chat"        title="Open Telegram"    sub="View Chat History" />
                  <ActionBtn icon="description" title="Download PDF"     sub="Full Transcript" />
                  <ActionBtn icon="graphic_eq"  title="Play AI Summary"  sub="Voice Note (0:45)"  wave full />
                </div>

                {/* Outcome metrics */}
                <div className="grid grid-cols-3 gap-3">
                  <MetricChip label="Fairness"  value={fairness !== null ? `${Math.round(fairness)}%` : "—"} accent />
                  <MetricChip label="Rounds"    value={String(totalRounds)} />
                  <MetricChip label="Duration"  value={duration} />
                </div>

                {/* Back link */}
                <div className="pt-2 border-t border-white/[0.06]">
                  <Link href={`/negotiation/${id}`} className="inline-flex items-center gap-1.5 text-xs text-slate-500 hover:text-[#B7A6FB] transition-colors font-mono">
                    <Icon name="arrow_back" className="text-sm" /> Back to negotiation detail
                  </Link>
                </div>
              </div>

              {/* ── RIGHT COLUMN: QR / UPI ── */}
              <div className="lg:w-80 flex-shrink-0 flex flex-col items-center justify-center gap-6 p-8 relative border-t lg:border-t-0 lg:border-l border-white/[0.06]" style={{ background:"rgba(0,0,0,0.35)" }}>
                <div className="absolute inset-0 bg-gradient-to-b from-transparent via-[#B7A6FB]/[0.03] to-transparent pointer-events-none" />

                <div className="text-center relative z-10">
                  <h3 className="text-white font-bold text-lg mb-1">Instant Settlement</h3>
                  <p className="text-slate-400 text-sm">Scan to pay via UPI</p>
                </div>

                {/* QR code frame */}
                <div className="relative z-10 p-1 rounded-xl" style={{ background:"linear-gradient(135deg,rgba(183,166,251,0.5),transparent)" }}>
                  <div className="bg-white p-3 rounded-lg shadow-2xl relative">
                    {/* Stylised QR placeholder */}
                    <div className="w-48 h-48 rounded flex items-center justify-center overflow-hidden" style={{ background:"#0d0a1a" }}>
                      <div className="grid grid-cols-7 gap-0.5 p-2 w-full h-full">
                        {Array.from({ length: 49 }).map((_, i) => (
                          <div key={i} className="rounded-[1px]"
                            style={{ background: Math.random() > 0.45 ? "#B7A6FB" : "transparent",
                              opacity: 0.85 + Math.random() * 0.15 }} />
                        ))}
                      </div>
                    </div>
                    {/* Rupee badge */}
                    <div className="absolute -bottom-3 -right-3 size-10 rounded-full flex items-center justify-center border-4" style={{ background:"#B7A6FB", borderColor:"#0d0a1a" }}>
                      <Icon name="currency_rupee" className="text-sm text-[#070312] font-bold" />
                    </div>
                  </div>
                </div>

                {/* UPI ID row */}
                <div className="w-full flex flex-col gap-3 relative z-10">
                  <div className="flex items-center justify-between p-3 rounded-lg border border-white/10 w-full" style={{ background:"rgba(255,255,255,0.04)" }}>
                    <div className="flex flex-col overflow-hidden">
                      <span className="text-[10px] text-slate-500 uppercase font-bold">UPI ID</span>
                      <span className="text-sm text-slate-200 font-mono truncate">{upiId}</span>
                    </div>
                    <CopyButton text={upiId} />
                  </div>

                  {/* Negotiation ID */}
                  <div className="flex items-center justify-between p-3 rounded-lg border border-white/10 w-full" style={{ background:"rgba(255,255,255,0.04)" }}>
                    <div className="flex flex-col overflow-hidden">
                      <span className="text-[10px] text-slate-500 uppercase font-bold">Negotiation ID</span>
                      <span className="text-xs text-slate-400 font-mono truncate">{id}</span>
                    </div>
                    <CopyButton text={id} />
                  </div>

                  <p className="text-[10px] text-center text-slate-600">
                    By paying, you agree to the terms resolved by the autonomous agents.
                  </p>
                </div>
              </div>

            </div>
          </div>

          {/* Footer pulse */}
          <div className="mt-8 flex items-center gap-2 opacity-40">
            <span className="size-2 rounded-full bg-[#B7A6FB] animate-pulse" />
            <span className="text-xs font-mono text-[#B7A6FB] uppercase tracking-[0.2em]">negoT8 Protocol Active</span>
          </div>

        </div>
      </div>
    </>
  );
}
