"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { FileText, ChevronRight } from "lucide-react"

interface Invoice {
  id: string
  invoice_number: string
  total_amount: number
  currency: string
  status_name: string
  issued_date: string
  due_date: string
  paid_at: string
}

export default function ClientInvoices() {
  const router = useRouter()
  const [invoices, setInvoices] = useState<Invoice[]>([])

  useEffect(() => {
    fetch("/client-portal/api/invoices", { credentials: "include" })
      .then((r) => r.json())
      .then((d) => setInvoices(d.invoices || []))
      .catch(() => {})
  }, [])

  return (
    <div>
      <h1 className="text-xl font-bold text-white mb-1">Invoices</h1>
      <p className="text-sm text-[#6a6a75] mb-6">View and download your invoices and receipts</p>

      {invoices.length === 0 ? (
        <div className="text-center py-16">
          <FileText className="h-10 w-10 text-[#2a2a35] mx-auto mb-3" />
          <p className="text-sm text-[#6a6a75]">No invoices yet</p>
        </div>
      ) : (
        <div className="space-y-3">
          {invoices.map((inv) => (
            <button
              key={inv.id}
              onClick={() => router.push(`/client-portal/invoices/${inv.id}`)}
              className="w-full bg-[#0d1117] border border-[#1a1a24] rounded-xl p-5 text-left hover:border-[#1BB0CE]/30 transition-all group"
            >
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <div className="flex items-center gap-3 mb-1">
                    <h3 className="text-white font-semibold">{inv.invoice_number}</h3>
                    <span className={`text-[10px] font-medium px-2 py-0.5 rounded-full ${
                      inv.status_name === "Paid" ? "bg-emerald-500/10 text-emerald-400" :
                      inv.status_name === "Overdue" ? "bg-red-500/10 text-red-400" :
                      "bg-amber-500/10 text-amber-400"
                    }`}>
                      {inv.status_name}
                    </span>
                  </div>
                  <div className="flex gap-4 mt-1">
                    <span className="text-sm text-white font-medium">
                      {inv.currency} {Number(inv.total_amount).toLocaleString()}
                    </span>
                    {inv.issued_date && (
                      <span className="text-[11px] text-[#6a6a75]">
                        Issued: {new Date(inv.issued_date).toLocaleDateString()}
                      </span>
                    )}
                  </div>
                </div>
                <ChevronRight className="h-5 w-5 text-[#2a2a35] group-hover:text-[#1BB0CE] transition-colors" />
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  )
}
