'use client';

import { format } from 'date-fns';
import {
  Calendar,
  CreditCard,
  Eye,
  FileText,
  MoreHorizontal,
  Send,
  Trash2,
  User,
} from 'lucide-react';
import Link from 'next/link';

import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
import { cn } from '@/lib/utils';
import type { InvoiceRow } from './invoice-columns';

const STATUS_COLORS: Record<string, string> = {
  draft: 'bg-gray-100 text-gray-700 border-gray-200',
  sent: 'bg-blue-100 text-blue-700 border-blue-200',
  paid: 'bg-green-100 text-green-700 border-green-200',
  overdue: 'bg-red-100 text-red-700 border-red-200',
  cancelled: 'bg-gray-100 text-gray-500 border-gray-200',
};

/**
 * Accent bar encodes payment completeness using `status`:
 *   paid     → green
 *   overdue  → orange (past-due unpaid)
 *   sent     → slate (awaiting payment, not yet overdue)
 *   draft    → slate-200
 *   other    → slate-300
 */
const STATUS_ACCENT: Record<string, string> = {
  paid: 'bg-emerald-400',
  overdue: 'bg-orange-400',
  sent: 'bg-slate-300',
  draft: 'bg-slate-200',
  cancelled: 'bg-slate-200',
};

function formatAmount(total: string, currency: string): string {
  try {
    return new Intl.NumberFormat('en', { style: 'currency', currency }).format(Number(total));
  } catch {
    return `${currency} ${total}`;
  }
}

interface InvoiceCardProps {
  invoice: InvoiceRow;
  portSlug: string;
  onSend?: (invoice: InvoiceRow) => void;
  onRecordPayment?: (invoice: InvoiceRow) => void;
  onDelete?: (invoice: InvoiceRow) => void;
}

export function InvoiceCard({
  invoice,
  portSlug,
  onSend,
  onRecordPayment,
  onDelete,
}: InvoiceCardProps) {
  const statusColor = STATUS_COLORS[invoice.status] ?? STATUS_COLORS.draft;
  const accentClass = STATUS_ACCENT[invoice.status] ?? 'bg-slate-300';

  let dueDateFormatted: string | null = null;
  try {
    dueDateFormatted = format(new Date(invoice.dueDate), 'MMM d, yyyy');
  } catch {
    dueDateFormatted = invoice.dueDate;
  }

  const amountFormatted = formatAmount(invoice.total, invoice.currency);

  return (
    <ListCard
      href={`/${portSlug}/invoices/${invoice.id}`}
      ariaLabel={`Invoice ${invoice.invoiceNumber}`}
      accentClassName={accentClass}
      actions={
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="h-9 w-9"
              onClick={(e) => e.stopPropagation()}
              aria-label={`Actions for invoice ${invoice.invoiceNumber}`}
            >
              <MoreHorizontal className="h-4 w-4" />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem asChild>
              <Link href={`/${portSlug}/invoices/${invoice.id}`}>
                <Eye className="mr-2 h-3.5 w-3.5" />
                View
              </Link>
            </DropdownMenuItem>
            {invoice.pdfFileId ? (
              <DropdownMenuItem asChild>
                <Link href={`/api/v1/files/${invoice.pdfFileId}/preview`} target="_blank">
                  <FileText className="mr-2 h-3.5 w-3.5" />
                  View PDF
                </Link>
              </DropdownMenuItem>
            ) : null}
            {invoice.status === 'draft' && onSend ? (
              <DropdownMenuItem onClick={() => onSend(invoice)}>
                <Send className="mr-2 h-3.5 w-3.5" />
                Send
              </DropdownMenuItem>
            ) : null}
            {(invoice.status === 'sent' || invoice.status === 'overdue') && onRecordPayment ? (
              <DropdownMenuItem onClick={() => onRecordPayment(invoice)}>
                <CreditCard className="mr-2 h-3.5 w-3.5" />
                Record Payment
              </DropdownMenuItem>
            ) : null}
            {invoice.status === 'draft' && onDelete ? (
              <DropdownMenuItem className="text-destructive" onClick={() => onDelete(invoice)}>
                <Trash2 className="mr-2 h-3.5 w-3.5" />
                Delete
              </DropdownMenuItem>
            ) : null}
          </DropdownMenuContent>
        </DropdownMenu>
      }
    >
      <div className="flex items-start gap-3">
        <ListCardAvatar icon={<FileText className="h-5 w-5" />} />
        <div className="min-w-0 flex-1">
          {/* Title row: invoice number + spacer for actions */}
          <div className="flex items-start justify-between gap-2">
            <h3 className="truncate font-mono text-base font-semibold tabular-nums tracking-tight text-foreground">
              {invoice.invoiceNumber}
            </h3>
            <span aria-hidden className="block h-9 w-9 shrink-0" />
          </div>

          {/* Client name */}
          <p className="mt-0.5 inline-flex items-center gap-1 truncate text-sm text-muted-foreground">
            <User className="h-3.5 w-3.5 shrink-0 text-muted-foreground/70" aria-hidden />
            <span className="truncate">{invoice.clientName}</span>
          </p>

          {/* Amount - prominent */}
          <p className="mt-1 text-base font-semibold tabular-nums text-foreground">
            {amountFormatted}
          </p>

          {/* Due date */}
          {dueDateFormatted ? (
            <div className="mt-0.5 flex flex-wrap items-center gap-x-2 text-xs text-muted-foreground">
              <ListCardMeta icon={<Calendar className="h-3 w-3" />}>
                Due {dueDateFormatted}
              </ListCardMeta>
            </div>
          ) : null}

          {/* Status pill */}
          <div className="mt-1.5">
            <span
              className={cn(
                'inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium capitalize',
                statusColor,
              )}
            >
              {invoice.status}
            </span>
          </div>
        </div>
      </div>
    </ListCard>
  );
}
