"use client";
import { useState } from "react";

interface Invoice {
  id: string;
  monthStart: string;
  totalHours: number;
  totalAmount: number;
  currency: string;
  sentAt: string | null;
  createdAt: string;
  client: { name: string; email: string | null };
}

interface Client { id: string; name: string; hourlyRate: number; }

export function InvoicesList({ invoices, clients }: { invoices: Invoice[]; clients: Client[] }) {
  const [generating, setGenerating] = useState<string | null>(null);
  const generableClients = clients.filter((c) => c.hourlyRate > 0);

  async function generate(clientId: string) {
    setGenerating(clientId);
    const res = await fetch(`/api/proxy/invoices/${clientId}/generate`, { method: "POST" });
    setGenerating(null);
    if (res.ok) {
      window.location.reload();
    } else {
      const err = await res.json().catch(() => ({}));
      alert(err.error || "Failed to generate. Check that client has hourly rate set and entries this month.");
    }
  }

  return (
    <div className="space-y-6">
      <div className="bg-ink-800/50 border border-white/10 rounded-xl p-5">
        <h3 className="font-bold mb-3">Generate invoice for this month</h3>
        {generableClients.length === 0 ? (
          <p className="text-sm text-white/50">Set hourly rates on the Clients page first.</p>
        ) : (
          <div className="grid grid-cols-2 gap-2">
            {generableClients.map((c) => (
              <button key={c.id} onClick={() => generate(c.id)} disabled={generating === c.id}
                className="bg-ink-700 hover:bg-ink-600 disabled:opacity-50 text-left px-4 py-2 rounded text-sm">
                {generating === c.id ? "Generating..." : `→ ${c.name}`}
              </button>
            ))}
          </div>
        )}
      </div>

      <div>
        <h2 className="font-bold text-lg mb-4">All invoices</h2>
        {invoices.length === 0 ? (
          <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>No invoices yet.</p>
          </div>
        ) : (
          <div className="space-y-2">
            {invoices.map((i) => (
              <div key={i.id} className="bg-ink-800/50 border border-white/10 rounded-lg p-4 flex items-center gap-4">
                <div className="flex-1">
                  <div className="font-semibold">{i.client.name}</div>
                  <div className="text-xs text-white/40">{new Date(i.monthStart).toLocaleString("en-US", { month: "long", year: "numeric" })} · {i.totalHours.toFixed(1)}h</div>
                </div>
                <div className="text-right">
                  <div className="font-bold">${i.totalAmount.toFixed(0)} {i.currency}</div>
                  <a href={`/api/proxy/invoices/${i.id}/pdf`} className="text-xs text-accent-400 hover:text-accent-300 underline">Download PDF</a>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
