'use client';

import { useMemo, useState } from 'react';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import { UserPayment } from '@/lib/api';
import { formatDateLong } from '@/lib/utils';
import { StatusPill, derivePaymentStatus } from './_shared/status';
import { pyg, isManualProvider } from './_shared/helpers';
import PayActions from './_shared/PayActions';

interface PaymentsTabProps {
  payments: UserPayment[];
  language: string;
  onChange: () => void;
}

type Filter = 'all' | 'paid' | 'pending';

export default function PaymentsTab({ payments, language: locale, onChange }: PaymentsTabProps) {
  const [filter, setFilter] = useState<Filter>('all');

  const filtered = useMemo(
    () =>
      payments.filter((p) => {
        if (filter === 'all') return true;
        if (filter === 'paid') return p.status === 'paid';
        return p.status !== 'paid' && p.status !== 'refunded';
      }),
    [payments, filter]
  );

  const totalPaid = payments
    .filter((p) => p.status === 'paid')
    .reduce((sum, p) => sum + Number(p.amount), 0);
  const totalPending = payments
    .filter((p) => p.status !== 'paid' && p.status !== 'refunded')
    .reduce((sum, p) => sum + Number(p.amount), 0);

  const providerLabel = (provider: string) => {
    const labels: Record<string, { en: string; es: string }> = {
      tpago: { en: 'TPago', es: 'TPago' },
      bank_transfer: { en: 'Bank transfer', es: 'Transferencia bancaria' },
      lightning: { en: 'Lightning (Bitcoin)', es: 'Lightning (Bitcoin)' },
      cash: { en: 'Cash', es: 'Efectivo' },
      bancard: { en: 'Card', es: 'Tarjeta' },
    };
    return labels[provider]?.[locale === 'es' ? 'es' : 'en'] || provider;
  };

  const chips: { id: Filter; label: { en: string; es: string } }[] = [
    { id: 'all', label: { en: 'All', es: 'Todos' } },
    { id: 'paid', label: { en: 'Paid', es: 'Pagados' } },
    { id: 'pending', label: { en: 'Pending', es: 'Pendientes' } },
  ];

  return (
    <div className="space-y-6">
      {/* Totals */}
      <div className="grid grid-cols-2 gap-4">
        <Card className="p-5">
          <p className="mb-1 text-sm text-gray-600">
            {locale === 'es' ? 'Total pagado' : 'Total paid'}
          </p>
          <p className="text-2xl font-bold text-green-700">{pyg(totalPaid)}</p>
        </Card>
        <Card className="p-5">
          <p className="mb-1 text-sm text-gray-600">
            {locale === 'es' ? 'Pendiente' : 'Pending'}
          </p>
          <p className="text-2xl font-bold text-red-700">{pyg(totalPending)}</p>
        </Card>
      </div>

      {/* Filter chips */}
      <div className="flex flex-wrap gap-2">
        {chips.map((chip) => (
          <button
            key={chip.id}
            onClick={() => setFilter(chip.id)}
            className={`rounded-full px-4 py-2 text-sm font-medium transition-colors ${
              filter === chip.id
                ? 'bg-primary-yellow text-primary-dark'
                : 'bg-secondary-gray text-gray-700 hover:bg-secondary-light-gray'
            }`}
          >
            {locale === 'es' ? chip.label.es : chip.label.en}
          </button>
        ))}
      </div>

      {/* Records */}
      {filtered.length === 0 ? (
        <Card className="p-8 text-center">
          <p className="text-gray-600">
            {locale === 'es' ? 'No hay pagos que mostrar' : 'No payments to show'}
          </p>
        </Card>
      ) : (
        <div className="space-y-3">
          {filtered.map((payment) => {
            const status = derivePaymentStatus(payment.status);
            const eventTitle =
              (locale === 'es' && payment.event?.titleEs
                ? payment.event.titleEs
                : payment.event?.title) || (locale === 'es' ? 'Evento' : 'Event');
            const canMarkPaid =
              payment.status === 'pending' && isManualProvider(payment.provider);
            const canRebook = payment.status === 'on_hold';
            return (
              <Card key={payment.id} className="p-4">
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                  <div className="min-w-0 flex-1">
                    <div className="mb-1 flex items-center gap-2">
                      <span className="font-semibold">
                        {pyg(Number(payment.amount), payment.currency)}
                      </span>
                      <StatusPill status={status} locale={locale} />
                    </div>
                    <div className="space-y-0.5 text-sm text-gray-600">
                      <p className="font-medium text-gray-800">{eventTitle}</p>
                      <p>
                        {providerLabel(payment.provider)} ·{' '}
                        {formatDateLong(payment.createdAt, locale as 'en' | 'es')}
                      </p>
                      {payment.reference && (
                        <p className="text-xs text-gray-500">
                          {locale === 'es' ? 'Ref' : 'Ref'}: {payment.reference}
                        </p>
                      )}
                    </div>
                  </div>

                  <div className="flex flex-shrink-0 flex-col items-stretch gap-2 sm:items-end">
                    {canRebook ? (
                      <PayActions
                        ticketId={payment.ticketId}
                        amount={Number(payment.amount)}
                        currency={payment.currency}
                        destination={eventTitle}
                        locale={locale}
                        onPaid={onChange}
                        layout="inline"
                        size="sm"
                        onHold
                      />
                    ) : (
                      canMarkPaid && (
                        <PayActions
                          ticketId={payment.ticketId}
                          amount={Number(payment.amount)}
                          currency={payment.currency}
                          destination={eventTitle}
                          locale={locale}
                          onPaid={onChange}
                          layout="inline"
                          size="sm"
                        />
                      )
                    )}
                    {payment.invoice && (
                      <a
                        href={payment.invoice.pdfUrl || '#'}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        <Button variant="outline" size="sm">
                          {locale === 'es' ? 'Factura' : 'Invoice'}
                        </Button>
                      </a>
                    )}
                  </div>
                </div>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}
