"use client"

import { useEffect, useState } from "react"
import { useParams } from "next/navigation"
import { FileText, Download } from "lucide-react"

interface InvoiceDetail {
  invoice: any
  items: any[]
  receipts: any[]
}

export default function InvoiceDetail() {
  const { id } = useParams<{ id: string }>()
  const [data, setData] = useState<InvoiceDetail | null>(null)

  useEffect(() => {
    fetch(`/client-portal/api/invoices/${id}`, { credentials: "include" })
      .then((r) => r.json())
      .then(setData)
      .catch(() => {})
  }, [id])

  if (!data) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="w-8 h-8 border-2 border-[#1BB0CE] border-t-transparent rounded-full animate-spin" />
      </div>
    )
  }

  const { invoice, items, receipts } = data

  return (
    <div>
      <h1 className="text-xl font-bold text-white mb-1">Invoice {invoice.invoice_number}</h1>
      <span className={`text-xs font-medium px-2 py-0.5 rounded-full ${
        invoice.status_name === "Paid" ? "bg-emerald-500/10 text-emerald-400" :
        invoice.status_name === "Overdue" ? "bg-red-500/10 text-red-400" :
        "bg-amber-500/10 text-amber-400"
      }`}>
        {invoice.status_name}
      </span>

      {/* Invoice details */}
      <div className="grid grid-cols-2 gap-4 mt-6 mb-6">
        <div className="bg-[#0d1117] border border-[#1a1a24] rounded-xl p-4">
          <span className="text-[11px] text-[#6a6a75] uppercase tracking-wider">Issued</span>
          <p className="text-white text-sm mt-1">
            {invoice.issued_date ? new Date(invoice.issued_date).toLocaleDateString() : "-"}
          </p>
        </div>
        <div className="bg-[#0d1117] border border-[#1a1a24] rounded-xl p-4">
          <span className="text-[11px] text-[#6a6a75] uppercase tracking-wider">Due</span>
          <p className="text-white text-sm mt-1">
            {invoice.due_date ? new Date(invoice.due_date).toLocaleDateString() : "-"}
          </p>
        </div>
      </div>

      {/* Line items */}
      <h2 className="text-base font-semibold text-white mb-3">Items</h2>
      <div className="bg-[#0d1117] border border-[#1a1a24] rounded-xl overflow-hidden mb-6">
        <table className="w-full">
          <thead>
            <tr className="border-b border-[#1a1a24]">
              <th className="text-left text-[11px] text-[#6a6a75] uppercase tracking-wider px-4 py-3">Description</th>
              <th className="text-right text-[11px] text-[#6a6a75] uppercase tracking-wider px-4 py-3">Qty</th>
              <th className="text-right text-[11px] text-[#6a6a75] uppercase tracking-wider px-4 py-3">Unit Price</th>
              <th className="text-right text-[11px] text-[#6a6a75] uppercase tracking-wider px-4 py-3">Total</th>
            </tr>
          </thead>
          <tbody>
            {items.map((item, i) => (
              <tr key={i} className="border-b border-[#1a1a24]/50">
                <td className="text-sm text-white px-4 py-3">{item.description}</td>
                <td className="text-sm text-white px-4 py-3 text-right">{item.quantity}</td>
                <td className="text-sm text-white px-4 py-3 text-right">
                  {invoice.currency} {Number(item.unit_price).toLocaleString()}
                </td>
                <td className="text-sm text-white px-4 py-3 text-right">
                  {invoice.currency} {Number(item.total_price).toLocaleString()}
                </td>
              </tr>
            ))}
          </tbody>
          <tfoot>
            {invoice.subtotal && (
              <tr>
                <td colSpan={3} className="text-right text-sm text-[#8a8a95] px-4 py-2">Subtotal</td>
                <td className="text-right text-sm text-white px-4 py-2">
                  {invoice.currency} {Number(invoice.subtotal).toLocaleString()}
                </td>
              </tr>
            )}
            {invoice.tax_amount > 0 && (
              <tr>
                <td colSpan={3} className="text-right text-sm text-[#8a8a95] px-4 py-2">Tax ({invoice.tax_percent}%)</td>
                <td className="text-right text-sm text-white px-4 py-2">
                  {invoice.currency} {Number(invoice.tax_amount).toLocaleString()}
                </td>
              </tr>
            )}
            <tr className="border-t border-[#1a1a24]">
              <td colSpan={3} className="text-right text-sm font-semibold text-white px-4 py-3">Total</td>
              <td className="text-right text-sm font-bold text-[#1BB0CE] px-4 py-3">
                {invoice.currency} {Number(invoice.total_amount).toLocaleString()}
              </td>
            </tr>
          </tfoot>
        </table>
      </div>

      {/* Receipts */}
      {receipts.length > 0 && (
        <>
          <h2 className="text-base font-semibold text-white mb-3">Receipts</h2>
          <div className="space-y-2">
            {receipts.map((r) => (
              <div key={r.id} className="bg-[#0d1117] border border-[#1a1a24] rounded-xl p-4 flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <FileText className="h-4 w-4 text-[#1BB0CE]" />
                  <div>
                    <span className="text-sm text-white">{r.receipt_number}</span>
                    <p className="text-[11px] text-[#6a6a75]">
                      {new Date(r.issued_at).toLocaleDateString()}
                    </p>
                  </div>
                </div>
                {r.file_url && (
                  <a
                    href={r.file_url}
                    target="_blank"
                    className="flex items-center gap-1.5 text-xs text-[#1BB0CE] hover:underline"
                  >
                    <Download className="h-3.5 w-3.5" />
                    Download
                  </a>
                )}
              </div>
            ))}
          </div>
        </>
      )}
    </div>
  )
}
