"use client";

import { useState } from "react";

interface Feedback {
  id: string;
  title: string;
  body: string | null;
  upvoteCount: number;
  status: string;
  submitterEmail: string | null;
  createdAt: string;
}

const STATUSES = [
  { key: "open", label: "Open", color: "bg-blue-500/10 text-blue-400 border-blue-500/30" },
  { key: "planned", label: "Planned", color: "bg-purple-500/10 text-purple-400 border-purple-500/30" },
  { key: "in_progress", label: "In Progress", color: "bg-yellow-500/10 text-yellow-400 border-yellow-500/30" },
  { key: "done", label: "Shipped", color: "bg-emerald-500/10 text-emerald-400 border-emerald-500/30" },
  { key: "closed", label: "Closed", color: "bg-white/5 text-white/40 border-white/10" },
];

export function FeedbackList({ initial }: { initial: Feedback[] }) {
  const [items, setItems] = useState<Feedback[]>(initial);
  const [filter, setFilter] = useState("all");

  async function setStatus(id: string, status: string) {
    const prev = items.find((f) => f.id === id)?.status;
    setItems((arr) => arr.map((f) => (f.id === id ? { ...f, status } : f)));
    const res = await fetch(`/api/proxy/feedback/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status }),
    });
    if (!res.ok && prev) {
      setItems((arr) => arr.map((f) => (f.id === id ? { ...f, status: prev } : f)));
    }
  }

  async function togglePublic(id: string, isPublic: boolean) {
    const res = await fetch(`/api/proxy/feedback/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ isPublic }),
    });
    if (!res.ok) return;
    setItems((arr) => arr.map((f) => (f.id === id ? { ...f, status: f.status } : f)));
  }

  const filtered = filter === "all" ? items : items.filter((f) => f.status === filter);

  if (items.length === 0) {
    return (
      <div className="bg-ink-800/30 border border-white/10 rounded-xl p-10 text-center text-white/50">
        <div className="text-3xl mb-3">💬</div>
        <p className="mb-1">No feedback yet.</p>
        <p className="text-xs text-white/40">Install the widget to start collecting.</p>
      </div>
    );
  }

  return (
    <>
      <div className="flex gap-1 mb-4 overflow-x-auto pb-1">
        <button
          onClick={() => setFilter("all")}
          className={`whitespace-nowrap text-sm px-3 py-1.5 rounded-lg border transition ${
            filter === "all" ? "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"
          }`}
        >
          All <span className="text-xs text-white/40 ml-1">{items.length}</span>
        </button>
        {STATUSES.map((s) => {
          const c = items.filter((f) => f.status === s.key).length;
          return (
            <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"
              }`}
            >
              {s.label} <span className="text-xs text-white/40 ml-1">{c}</span>
            </button>
          );
        })}
      </div>
      <div className="space-y-2">
        {filtered.map((f) => (
          <div key={f.id} className="bg-ink-800/50 border border-white/10 rounded-lg p-4 flex items-start gap-4">
            <div className="text-center min-w-[44px]">
              <div className="text-2xl font-bold">{f.upvoteCount}</div>
              <div className="text-xs text-white/40 uppercase">votes</div>
            </div>
            <div className="flex-1 min-w-0">
              <h3 className="font-semibold mb-1">{f.title}</h3>
              {f.body && <p className="text-sm text-white/60 mb-2 whitespace-pre-wrap">{f.body}</p>}
              <div className="text-xs text-white/40 flex items-center gap-3 flex-wrap">
                <span>{f.submitterEmail || "anonymous"}</span>
                <span>·</span>
                <span>{new Date(f.createdAt).toLocaleDateString()}</span>
              </div>
            </div>
            <select
              value={f.status}
              onChange={(e) => setStatus(f.id, e.target.value)}
              className="bg-ink-900 border border-white/10 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:border-brand-500"
            >
              {STATUSES.map((s) => (
                <option key={s.key} value={s.key}>{s.label}</option>
              ))}
            </select>
          </div>
        ))}
      </div>
    </>
  );
}
