'use client';

import clsx from 'clsx';
import {
  CheckCircleIcon,
  ArrowUturnLeftIcon,
  UserGroupIcon,
} from '@heroicons/react/24/outline';
import type { DoorAttendee, DoorPaymentMethod } from '@/lib/api';
import { formatCurrency, parseDate, EVENT_TIMEZONE } from '@/lib/utils';
import { PaymentButtons } from './PaymentButtons';

function checkinTime(checkinAt: string | null): string {
  if (!checkinAt) return '';
  return parseDate(checkinAt).toLocaleTimeString([], {
    hour: '2-digit',
    minute: '2-digit',
    timeZone: EVENT_TIMEZONE,
  });
}

const METHOD_LABELS: Record<DoorPaymentMethod, string> = {
  cash: 'cash',
  bitcoin: 'bitcoin',
  transfer: 'transfer',
  guest: 'guest',
};

/** The second line of a row: everything staff needs to decide in one glance. */
function statusLine(attendee: DoorAttendee, currency: string): string {
  if (attendee.status === 'cancelled') return 'Cancelled';
  if (attendee.checkedIn) {
    const time = checkinTime(attendee.checkinAt);
    const how = attendee.doorMethod ? ` · paid ${METHOD_LABELS[attendee.doorMethod]}` : '';
    return time ? `Checked in ${time}${how}` : `Checked in${how}`;
  }

  const parts: string[] = [];
  if (attendee.paymentStatus === 'comp') parts.push('Guest');
  else if (attendee.paymentStatus === 'paid') parts.push('Paid');
  else parts.push(`Unpaid · ${formatCurrency(attendee.amountDue, currency)} due`);

  if (attendee.isGroupBooking) parts.push('group booking');
  if (attendee.status === 'pending') parts.push('pending');
  return parts.join(' · ');
}

export function AttendeeRow({
  attendee,
  currency,
  price,
  expanded,
  flashing,
  busy,
  onTap,
  onPay,
}: {
  attendee: DoorAttendee;
  currency: string;
  price: number;
  expanded: boolean;
  flashing: boolean;
  busy: boolean;
  onTap: () => void;
  onPay: (method: DoorPaymentMethod, amount: number) => void;
}) {
  const isCancelled = attendee.status === 'cancelled';
  const settled = attendee.paymentStatus === 'paid' || attendee.paymentStatus === 'comp';
  // A settled, not-yet-arrived attendee is the one-tap case: the whole row checks
  // them in. Everyone else opens the tenders inline instead.
  const isOneTap = !isCancelled && !attendee.checkedIn && settled;

  return (
    <div
      className={clsx(
        'rounded-2xl border transition-colors',
        flashing
          ? 'bg-emerald-600 border-emerald-400'
          : attendee.checkedIn || isCancelled
            ? 'bg-gray-900 border-gray-800'
            : 'bg-gray-800 border-gray-700',
      )}
    >
      <button
        onClick={onTap}
        disabled={busy}
        className="w-full text-left px-4 py-3 min-h-[64px] flex items-center gap-3 active:scale-[0.99] transition-transform disabled:opacity-60"
      >
        <div className="flex-1 min-w-0">
          <p
            className={clsx(
              'font-bold text-lg truncate',
              flashing ? 'text-white' : attendee.checkedIn || isCancelled ? 'text-gray-400' : 'text-white',
            )}
          >
            {attendee.fullName}
          </p>
          <p
            className={clsx(
              'text-sm truncate flex items-center gap-1.5',
              flashing
                ? 'text-emerald-50'
                : isCancelled
                  ? 'text-red-400'
                  : attendee.checkedIn
                    ? 'text-gray-500'
                    : attendee.paymentStatus === 'unpaid'
                      ? 'text-amber-400'
                      : 'text-gray-400',
            )}
          >
            {attendee.isGroupBooking && !attendee.checkedIn && <UserGroupIcon className="w-4 h-4 flex-shrink-0" />}
            {statusLine(attendee, currency)}
          </p>
        </div>

        {flashing ? (
          <CheckCircleIcon className="w-8 h-8 text-white flex-shrink-0" />
        ) : attendee.checkedIn ? (
          <CheckCircleIcon className="w-7 h-7 text-emerald-500/60 flex-shrink-0" />
        ) : isCancelled ? (
          <span className="flex-shrink-0 text-[10px] font-bold uppercase tracking-wide px-2 py-1 rounded-full bg-red-950 text-red-400">
            Cancelled
          </span>
        ) : isOneTap ? (
          <span className="flex-shrink-0 text-xs font-bold uppercase tracking-wide text-primary-yellow">
            Check in
          </span>
        ) : (
          <span className="flex-shrink-0 text-xs font-bold uppercase tracking-wide text-amber-400">
            Collect
          </span>
        )}
      </button>

      {expanded && !attendee.checkedIn && (
        <div className="px-3 pb-3 pt-1 space-y-2">
          {isCancelled && (
            <p className="text-xs text-gray-400 px-1 flex items-center gap-1.5">
              <ArrowUturnLeftIcon className="w-4 h-4" />
              Reactivate as a walk-in — pick how they are paying.
            </p>
          )}
          <PaymentButtons price={price} currency={currency} onPay={onPay} disabled={busy} />
        </div>
      )}

      {expanded && attendee.checkedIn && (
        <div className="px-4 pb-3 -mt-1">
          <p className="text-sm text-gray-400">
            Already checked in
            {attendee.checkinAt ? ` at ${checkinTime(attendee.checkinAt)}` : ''}
            {attendee.checkedInBy ? ` by ${attendee.checkedInBy}` : ''}.
          </p>
        </div>
      )}
    </div>
  );
}
