"use client";

import { useEffect, useMemo, useState } from "react";

interface Board { id: string; name: string; slug: string; publicKey: string; }
interface Feedback {
  id: string;
  title: string;
  body: string | null;
  upvoteCount: number;
  status: string;
  createdAt: string;
}

const STATUSES = [
  { key: "all", label: "All", emoji: "📋" },
  { key: "open", label: "Open", emoji: "💡" },
  { key: "planned", label: "Planned", emoji: "📌" },
  { key: "in_progress", label: "In Progress", emoji: "🔧" },
  { key: "done", label: "Shipped", emoji: "✅" },
];

const STATUS_COLOR: Record<string, string> = {
  open: "bg-blue-500/10 text-blue-400 border-blue-500/30",
  planned: "bg-purple-500/10 text-purple-400 border-purple-500/30",
  in_progress: "bg-yellow-500/10 text-yellow-400 border-yellow-500/30",
  done: "bg-emerald-500/10 text-emerald-400 border-emerald-500/30",
  closed: "bg-white/5 text-white/40 border-white/10",
};

function timeAgo(iso: string): string {
  const ms = Date.now() - new Date(iso).getTime();
  const s = Math.floor(ms / 1000);
  if (s < 60) return `${s}s ago`;
  const m = Math.floor(s / 60);
  if (m < 60) return `${m}m ago`;
  const h = Math.floor(m / 60);
  if (h < 24) return `${h}h ago`;
  const d = Math.floor(h / 24);
  if (d < 30) return `${d}d ago`;
  const mo = Math.floor(d / 30);
  return `${mo}mo ago`;
}

function getOrCreateAnonId(): string {
  if (typeof window === "undefined") return "anon";
  let id = localStorage.getItem("ik_anon_id");
  if (!id) {
    id = "anon_" + crypto.randomUUID();
    localStorage.setItem("ik_anon_id", id);
  }
  return id;
}

export function Roadmap({ board, initialFeedback }: { board: Board; initialFeedback: Feedback[] }) {
  const [feedback, setFeedback] = useState<Feedback[]>(initialFeedback);
  const [filter, setFilter] = useState("all");
  const [votedIds, setVotedIds] = useState<Set<string>>(new Set());
  const [showSubmit, setShowSubmit] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [submitOk, setSubmitOk] = useState(false);

  useEffect(() => {
    if (typeof window !== "undefined") {
      const stored = JSON.parse(localStorage.getItem("ik_votes_" + board.publicKey) || "[]");
      setVotedIds(new Set(stored));
    }
  }, [board.publicKey]);

  const filtered = useMemo(() => {
    const list = filter === "all" ? feedback : feedback.filter((f) => f.status === filter);
    return list.sort((a, b) => b.upvoteCount - a.upvoteCount || b.createdAt.localeCompare(a.createdAt));
  }, [feedback, filter]);

  const counts = useMemo(() => {
    const m: Record<string, number> = { all: feedback.length };
    for (const s of STATUSES.slice(1)) m[s.key] = 0;
    for (const f of feedback) m[f.status] = (m[f.status] || 0) + 1;
    return m;
  }, [feedback]);

  async function upvote(fid: string) {
    if (votedIds.has(fid)) return;
    const anonId = getOrCreateAnonId();
    setFeedback((arr) => arr.map((f) => (f.id === fid ? { ...f, upvoteCount: f.upvoteCount + 1 } : f)));
    const next = new Set(votedIds);
    next.add(fid);
    setVotedIds(next);
    localStorage.setItem("ik_votes_" + board.publicKey, JSON.stringify([...next]));
    try {
      await fetch(`/v1/votes/${fid}/upvote`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ anonymousId: anonId }),
      });
    } catch {}
  }

  async function submitFeedback(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setSubmitting(true);
    const f = new FormData(e.currentTarget);
    const title = String(f.get("title") || "").trim();
    const body = String(f.get("body") || "").trim();
    const email = String(f.get("email") || "").trim();
    if (title.length < 3) { setSubmitting(false); return; }
    try {
      const res = await fetch(`/v1/feedback/public/${board.publicKey}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ title, body: body || undefined, email: email || undefined }),
      });
      if (res.ok) {
        setSubmitOk(true);
        (e.target as HTMLFormElement).reset();
        setTimeout(() => { setShowSubmit(false); setSubmitOk(false); }, 1800);
      }
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <main className="min-h-screen bg-ink-950 text-white">
      <header className="border-b border-white/5 backdrop-blur sticky top-0 z-30 bg-ink-950/85">
        <div className="max-w-3xl mx-auto px-6 h-14 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-7 h-7 rounded-md bg-brand-500 grid place-items-center text-ink-950 font-bold">
              {board.name.charAt(0)}
            </div>
            <h1 className="font-bold tracking-tight">{board.name}</h1>
            <span className="text-xs text-white/30 hidden sm:inline">· roadmap</span>
          </div>
          <a href="https://inbox.mindie.dev" target="_blank" rel="noreferrer"
             className="text-xs text-white/40 hover:text-white">
            Powered by InboxKit
          </a>
        </div>
      </header>

      <div className="max-w-3xl mx-auto px-6 py-8">
        <div className="mb-6 flex items-center justify-between gap-3">
          <p className="text-white/50 text-sm">
            Public feature requests. Upvote what matters · {feedback.length} item{feedback.length === 1 ? "" : "s"}
          </p>
          <button
            onClick={() => setShowSubmit(true)}
            className="bg-brand-500 hover:bg-brand-400 text-ink-950 font-semibold text-sm px-4 py-2 rounded-lg"
          >
            + Suggest
          </button>
        </div>

        <div className="flex gap-1 mb-6 overflow-x-auto pb-1">
          {STATUSES.map((s) => (
            <button
              key={s.key}
              onClick={() => setFilter(s.key)}
              className={`whitespace-nowrap text-sm px-3 py-1.5 rounded-lg border transition ${
                filter === s.key
                  ? "bg-brand-500/15 text-brand-400 border-brand-500/40"
                  : "bg-ink-800/40 text-white/60 border-white/5 hover:border-white/10"
              }`}
            >
              <span className="mr-1.5">{s.emoji}</span>
              {s.label}
              {(counts[s.key] ?? 0) > 0 && (
                <span className="ml-2 text-xs text-white/40">{counts[s.key]}</span>
              )}
            </button>
          ))}
        </div>

        {filtered.length === 0 ? (
          <div className="bg-ink-800/40 border border-white/10 rounded-xl p-10 text-center text-white/50">
            <div className="text-4xl mb-3">🌱</div>
            <p>No {filter === "all" ? "" : filter + " "}items yet.</p>
            <p className="text-sm mt-2">Be the first to suggest something.</p>
          </div>
        ) : (
          <div className="space-y-2">
            {filtered.map((f) => (
              <div key={f.id}
                   className="bg-ink-800/50 border border-white/10 hover:border-brand-500/30 transition rounded-xl p-4 flex items-start gap-4">
                <button
                  onClick={() => upvote(f.id)}
                  disabled={votedIds.has(f.id)}
                  className={`text-center min-w-[56px] py-2 rounded-lg border transition ${
                    votedIds.has(f.id)
                      ? "bg-brand-500/15 border-brand-500/40 cursor-default"
                      : "bg-ink-900/50 border-white/10 hover:border-brand-500/40 hover:bg-brand-500/10 cursor-pointer"
                  }`}
                  title={votedIds.has(f.id) ? "You voted" : "Upvote"}
                >
                  <div className={`text-lg leading-none mb-0.5 ${votedIds.has(f.id) ? "text-brand-400" : "text-white/60"}`}>
                    ▲
                  </div>
                  <div className={`text-sm font-bold ${votedIds.has(f.id) ? "text-brand-400" : "text-white"}`}>
                    {f.upvoteCount}
                  </div>
                </button>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap mb-1">
                    <h3 className="font-semibold">{f.title}</h3>
                    <span className={`text-xs px-2 py-0.5 rounded-full font-mono border ${STATUS_COLOR[f.status] || "bg-white/5 text-white/40 border-white/10"}`}>
                      {f.status.replace("_", " ")}
                    </span>
                  </div>
                  {f.body && <p className="text-sm text-white/60 mb-2 whitespace-pre-wrap">{f.body}</p>}
                  <p className="text-xs text-white/30">{timeAgo(f.createdAt)}</p>
                </div>
              </div>
            ))}
          </div>
        )}

        <footer className="mt-12 pt-8 border-t border-white/5 text-center text-xs text-white/30">
          Want a public roadmap like this for your product?{" "}
          <a href="https://inbox.mindie.dev" className="text-brand-400 hover:text-brand-300">Start free on InboxKit →</a>
        </footer>
      </div>

      {showSubmit && (
        <div className="fixed inset-0 z-50 bg-ink-950/80 backdrop-blur-sm flex items-center justify-center px-4"
             onClick={(e) => { if (e.target === e.currentTarget) setShowSubmit(false); }}>
          <form onSubmit={submitFeedback}
                className="w-full max-w-md bg-ink-900 border border-white/10 rounded-2xl p-6 shadow-2xl">
            {submitOk ? (
              <div className="text-center py-8">
                <div className="text-5xl mb-3">✓</div>
                <p className="font-bold mb-1">Thanks!</p>
                <p className="text-sm text-white/60">Your suggestion is in.</p>
              </div>
            ) : (
              <>
                <h3 className="font-bold text-lg mb-1">Suggest a feature</h3>
                <p className="text-sm text-white/50 mb-5">Anonymous unless you add an email.</p>
                <input name="title" required minLength={3} maxLength={280}
                       placeholder="One-line summary"
                       className="w-full px-3 py-2 bg-ink-800 border border-white/10 rounded-lg mb-3 placeholder-white/30 focus:outline-none focus:border-brand-500" />
                <textarea name="body" maxLength={4000} rows={4}
                          placeholder="Optional details — what would this unlock for you?"
                          className="w-full px-3 py-2 bg-ink-800 border border-white/10 rounded-lg mb-3 placeholder-white/30 focus:outline-none focus:border-brand-500 resize-y" />
                <input name="email" type="email"
                       placeholder="Email (optional, for follow-up)"
                       className="w-full px-3 py-2 bg-ink-800 border border-white/10 rounded-lg mb-5 placeholder-white/30 focus:outline-none focus:border-brand-500" />
                <div className="flex gap-2">
                  <button type="button" onClick={() => setShowSubmit(false)}
                          className="flex-1 py-2.5 rounded-lg font-semibold text-white/60 hover:text-white bg-ink-800 border border-white/10">
                    Cancel
                  </button>
                  <button type="submit" disabled={submitting}
                          className="flex-1 py-2.5 rounded-lg font-semibold bg-brand-500 hover:bg-brand-400 text-ink-950 disabled:opacity-50">
                    {submitting ? "Sending..." : "Submit"}
                  </button>
                </div>
              </>
            )}
          </form>
        </div>
      )}
    </main>
  );
}
