'use client';

import { format } from 'date-fns';
import { Archive, Calendar, Eye, MoreHorizontal, Pencil, Receipt, Tag } 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 { formatCurrency } from '@/lib/utils/currency';
import type { ExpenseRow } from './expense-columns';

const PAYMENT_STATUS_COLORS: Record<string, string> = {
  unpaid: 'bg-red-100 text-red-700 border-red-200',
  paid: 'bg-green-100 text-green-700 border-green-200',
  partial: 'bg-yellow-100 text-yellow-700 border-yellow-200',
  reconciled: 'bg-green-100 text-green-700 border-green-200',
  flagged: 'bg-rose-100 text-rose-700 border-rose-200',
  pending: 'bg-amber-100 text-amber-700 border-amber-200',
};

/**
 * Accent bar by payment status:
 *   paid / reconciled → emerald
 *   pending           → amber
 *   flagged           → rose
 *   other / null      → slate
 * If duplicateOf is set, override to amber-500.
 */
function deriveAccent(status: string | null, duplicateOf: string | null): string {
  if (duplicateOf) return 'bg-amber-500';
  switch (status) {
    case 'paid':
    case 'reconciled':
      return 'bg-emerald-400';
    case 'pending':
      return 'bg-amber-400';
    case 'flagged':
      return 'bg-rose-400';
    default:
      return 'bg-slate-300';
  }
}

const formatAmount = (amount: string, currency: string) => formatCurrency(amount, currency);

interface ExpenseCardProps {
  expense: ExpenseRow;
  portSlug: string;
  onEdit: (expense: ExpenseRow) => void;
  onArchive: (expense: ExpenseRow) => void;
}

export function ExpenseCard({ expense, portSlug, onEdit, onArchive }: ExpenseCardProps) {
  const accentClass = deriveAccent(expense.paymentStatus, expense.duplicateOf);

  const title =
    expense.establishmentName ??
    (expense.description ? expense.description.slice(0, 40) : null) ??
    'Untitled expense';

  // Subtitle: category (capitalized) or "{paymentMethod} by {payer}"
  let subtitle: string | null = null;
  if (expense.category) {
    subtitle = expense.category.replace(/_/g, ' ');
    // Capitalize first letter
    subtitle = subtitle.charAt(0).toUpperCase() + subtitle.slice(1);
  } else if (expense.paymentMethod || expense.payer) {
    const parts: string[] = [];
    if (expense.paymentMethod) parts.push(expense.paymentMethod);
    if (expense.payer) parts.push(`by ${expense.payer}`);
    subtitle = parts.join(' ');
  }
  const hasCategory = !!expense.category;

  let dateFormatted: string | null = null;
  try {
    dateFormatted = format(new Date(expense.expenseDate), 'MMM d, yyyy');
  } catch {
    dateFormatted = expense.expenseDate;
  }

  const amountFormatted = formatAmount(expense.amount, expense.currency);

  const statusColor = expense.paymentStatus
    ? (PAYMENT_STATUS_COLORS[expense.paymentStatus] ??
      'bg-muted text-muted-foreground border-muted')
    : null;

  return (
    <ListCard
      href={`/${portSlug}/expenses/${expense.id}`}
      ariaLabel={`Expense: ${title}`}
      accentClassName={accentClass}
      actions={
        <DropdownMenu>
          <DropdownMenuTrigger asChild>
            <Button
              variant="ghost"
              size="icon"
              className="h-9 w-9"
              onClick={(e) => e.stopPropagation()}
              aria-label={`Actions for expense: ${title}`}
            >
              <MoreHorizontal className="h-4 w-4" aria-hidden />
            </Button>
          </DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem asChild>
              <Link href={`/${portSlug}/expenses/${expense.id}`}>
                <Eye className="mr-2 h-3.5 w-3.5" aria-hidden />
                View
              </Link>
            </DropdownMenuItem>
            <DropdownMenuItem onClick={() => onEdit(expense)}>
              <Pencil className="mr-2 h-3.5 w-3.5" aria-hidden />
              Edit
            </DropdownMenuItem>
            <DropdownMenuItem className="text-destructive" onClick={() => onArchive(expense)}>
              <Archive className="mr-2 h-3.5 w-3.5" aria-hidden />
              Archive
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      }
    >
      <div className="flex items-start gap-3">
        <ListCardAvatar icon={<Receipt className="h-5 w-5" aria-hidden />} />
        <div className="min-w-0 flex-1">
          {/* Title row + spacer for actions button */}
          <div className="flex items-start justify-between gap-2">
            <h3 className="truncate text-base font-semibold tracking-tight text-foreground">
              {title}
            </h3>
            <span aria-hidden className="block h-9 w-9 shrink-0" />
          </div>

          {/* Category / payer subtitle */}
          {subtitle ? (
            <p className="mt-0.5 inline-flex items-center gap-1 truncate text-sm text-muted-foreground">
              {hasCategory ? (
                <Tag className="h-3.5 w-3.5 shrink-0 text-muted-foreground/70" aria-hidden />
              ) : null}
              <span className="truncate">{subtitle}</span>
            </p>
          ) : null}

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

          {/* Date meta */}
          {dateFormatted ? (
            <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" aria-hidden />}>
                {dateFormatted}
              </ListCardMeta>
            </div>
          ) : null}

          {/* Status + duplicate pills */}
          <div className="mt-1.5 flex flex-wrap items-center gap-1.5">
            {statusColor && expense.paymentStatus ? (
              <span
                className={cn(
                  'inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium capitalize',
                  statusColor,
                )}
              >
                {expense.paymentStatus}
              </span>
            ) : null}

            {expense.duplicateOf ? (
              <span className="inline-flex items-center rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700">
                Possible duplicate
              </span>
            ) : null}
          </div>
        </div>
      </div>
    </ListCard>
  );
}
