"use client";

import { useEffect, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";

interface Signup {
  projectSlug: string;
  name: string;
  email: string;
  tier?: string;
  receivedAt: string;
}

export function CrowdfundAdmin() {
  const [signups, setSignups] = useState<Signup[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>("");

  useEffect(() => {
    (async () => {
      try {
        const resp = await fetch("/api/invest/signup");
        const data = await resp.json();
        if (!resp.ok) throw new Error(data.error || "Failed");
        setSignups(data.entries ?? []);
      } catch (e) {
        setError(e instanceof Error ? e.message : "Unknown error");
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  function exportCsv() {
    const rows = [
      ["Project", "Name", "Email", "Tier", "Received"],
      ...signups.map((s) => [s.projectSlug, s.name, s.email, s.tier ?? "", s.receivedAt]),
    ];
    const csv = rows
      .map((r) => r.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(","))
      .join("\n");
    const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `sag-investor-signups-${new Date().toISOString().slice(0, 10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  const byProject = signups.reduce<Record<string, number>>((acc, s) => {
    acc[s.projectSlug] = (acc[s.projectSlug] ?? 0) + 1;
    return acc;
  }, {});

  return (
    <Card>
      <CardContent className="p-6">
        <div className="flex items-center justify-between flex-wrap gap-2 mb-4">
          <div>
            <h2 className="text-base font-semibold">Investor signups</h2>
            <p className="text-xs text-muted-foreground">
              Captured via /invest/[slug] interest forms.
              {Object.keys(byProject).length > 0 && (
                <> Counts: {Object.entries(byProject).map(([k, v]) => `${k}: ${v}`).join(" · ")}</>
              )}
            </p>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" disabled={signups.length === 0} onClick={exportCsv}>
              Export CSV
            </Button>
          </div>
        </div>

        {loading ? (
          <div className="text-sm text-muted-foreground">Loading...</div>
        ) : error ? (
          <div className="text-sm text-destructive">{error}</div>
        ) : signups.length === 0 ? (
          <div className="rounded-md border border-dashed p-8 text-center text-sm text-muted-foreground">
            No signups yet. Once visitors submit interest on a pitch page, they’ll appear here.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead className="border-b bg-muted/40">
                <tr>
                  <th className="text-left p-3 font-medium">When</th>
                  <th className="text-left p-3 font-medium">Project</th>
                  <th className="text-left p-3 font-medium">Name</th>
                  <th className="text-left p-3 font-medium">Email</th>
                  <th className="text-left p-3 font-medium">Tier</th>
                </tr>
              </thead>
              <tbody>
                {[...signups]
                  .sort((a, b) => b.receivedAt.localeCompare(a.receivedAt))
                  .map((s, i) => (
                    <tr key={i} className="border-b last:border-b-0 hover:bg-muted/20">
                      <td className="p-3 text-xs">{new Date(s.receivedAt).toLocaleString()}</td>
                      <td className="p-3 text-xs">
                        <Badge variant="outline">{s.projectSlug}</Badge>
                      </td>
                      <td className="p-3">{s.name || <span className="text-muted-foreground">—</span>}</td>
                      <td className="p-3 font-mono text-xs">{s.email}</td>
                      <td className="p-3 text-xs">
                        {s.tier ? <Badge variant="info" className="text-[10px]">{s.tier}</Badge> : <span className="text-muted-foreground">—</span>}
                      </td>
                    </tr>
                  ))}
              </tbody>
            </table>
          </div>
        )}
      </CardContent>
    </Card>
  );
}
