"use client";

import { useState } from "react";
import { Trash2, ChevronDown } from "lucide-react";

type Lead = {
  id: string;
  name: string;
  email: string;
  subject: string;
  message: string;
  status: string;
  createdAt: Date;
};

const STATUS_OPTIONS = ["NEW", "CONTACTED", "QUALIFIED", "CLOSED"];

const statusStyles: Record<string, string> = {
  NEW: "bg-brand-cyan/20 text-brand-cyan",
  CONTACTED: "bg-yellow-400/20 text-yellow-400",
  QUALIFIED: "bg-green-500/20 text-green-400",
  CLOSED: "bg-brand-muted/20 text-brand-muted",
};

export function LeadsTable({ initialLeads }: { initialLeads: Lead[] }) {
  const [leads, setLeads] = useState(initialLeads);
  const [expanded, setExpanded] = useState<string | null>(null);
  const [filter, setFilter] = useState("ALL");

  async function updateStatus(id: string, status: string) {
    const res = await fetch(`/api/admin/leads/${id}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status }),
    });
    if (res.ok) {
      setLeads((prev) => prev.map((l) => (l.id === id ? { ...l, status } : l)));
    }
  }

  async function deleteLead(id: string) {
    if (!confirm("Delete this lead permanently?")) return;
    const res = await fetch(`/api/admin/leads/${id}`, { method: "DELETE" });
    if (res.ok) setLeads((prev) => prev.filter((l) => l.id !== id));
  }

  const filtered = filter === "ALL" ? leads : leads.filter((l) => l.status === filter);

  return (
    <div>
      {/* Filter */}
      <div className="flex gap-2 mb-6 flex-wrap">
        {["ALL", ...STATUS_OPTIONS].map((s) => (
          <button
            key={s}
            onClick={() => setFilter(s)}
            className={`px-4 py-2 rounded-full text-xs font-bold uppercase tracking-widest transition-all ${
              filter === s
                ? "bg-brand-cyan text-brand-dark"
                : "bg-white/5 text-brand-muted hover:bg-white/10"
            }`}
          >
            {s}
          </button>
        ))}
      </div>

      {filtered.length === 0 ? (
        <div className="text-brand-muted text-sm py-10 text-center">No leads found.</div>
      ) : (
        <div className="space-y-3">
          {filtered.map((lead) => (
            <div
              key={lead.id}
              className="bg-[#0F172A]/60 border border-white/5 rounded-2xl overflow-hidden"
            >
              <div
                className="flex items-center justify-between px-6 py-4 cursor-pointer"
                onClick={() => setExpanded(expanded === lead.id ? null : lead.id)}
              >
                <div className="flex items-center gap-4">
                  <div className="w-10 h-10 rounded-xl bg-brand-cyan/10 flex items-center justify-center text-brand-cyan font-bold text-sm">
                    {lead.name.charAt(0).toUpperCase()}
                  </div>
                  <div>
                    <p className="font-semibold">{lead.name}</p>
                    <p className="text-sm text-brand-muted">{lead.email}</p>
                  </div>
                </div>

                <div className="flex items-center gap-4">
                  <span className="text-xs text-brand-muted hidden md:block">{lead.subject}</span>

                  <select
                    value={lead.status}
                    onChange={(e) => { e.stopPropagation(); updateStatus(lead.id, e.target.value); }}
                    onClick={(e) => e.stopPropagation()}
                    className={`text-xs font-bold px-3 py-1.5 rounded-full border-0 outline-none cursor-pointer ${statusStyles[lead.status] ?? "bg-white/10 text-white"}`}
                  >
                    {STATUS_OPTIONS.map((s) => (
                      <option key={s} value={s} className="bg-[#0F172A] text-white">
                        {s}
                      </option>
                    ))}
                  </select>

                  <time className="text-xs text-brand-muted hidden lg:block">
                    {new Date(lead.createdAt).toLocaleDateString()}
                  </time>

                  <button
                    onClick={(e) => { e.stopPropagation(); deleteLead(lead.id); }}
                    className="p-2 rounded-lg text-brand-muted hover:text-red-400 hover:bg-red-500/10 transition-all"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>

                  <ChevronDown
                    className={`w-4 h-4 text-brand-muted transition-transform ${expanded === lead.id ? "rotate-180" : ""}`}
                  />
                </div>
              </div>

              {expanded === lead.id && (
                <div className="px-6 py-4 border-t border-white/5 bg-white/[0.02]">
                  <p className="text-sm text-brand-muted font-bold uppercase tracking-widest mb-2">Message</p>
                  <p className="text-sm text-white/80 whitespace-pre-wrap">{lead.message}</p>
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
