import type { CheckInResult, Guest } from '../../types/guest';
import { cardTypeLabel, formatTime } from '../../utils/format';

interface Props {
  result:          CheckInResult;
  onDismiss:       () => void;
  onNextAttendee?: () => void;
  isProcessing?:   boolean;
}

const isMulti = (g: Guest) => g.total_attendees > 1;
const isDone  = (g: Guest) => g.checked_in_count >= g.total_attendees;

export function ScanResult({ result, onDismiss, onNextAttendee, isProcessing = false }: Props) {
  const { status, guest, message } = result;

  const isSuccess   = status === 'checked_in';
  const isDuplicate = status === 'already_checked_in';

  const keepOpen  = isSuccess && !!guest && isMulti(guest) && !isDone(guest);
  const fullyDone = isSuccess && !!guest && isDone(guest);

  /* ── theme ─────────────────────────────────────────────────────────────── */
  const theme = isSuccess
    ? { band: 'bg-emerald-500', shadow: 'shadow-emerald-500/25', pill: 'bg-emerald-500', bar: 'bg-emerald-500', icon: 'M5 13l4 4L19 7' }
    : isDuplicate
    ? { band: 'bg-amber-500',   shadow: 'shadow-amber-500/25',   pill: 'bg-amber-500',   bar: 'bg-amber-400',   icon: 'M12 9v4m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z' }
    : { band: 'bg-red-500',     shadow: 'shadow-red-500/25',     pill: 'bg-red-500',     bar: 'bg-red-400',     icon: 'M6 18L18 6M6 6l12 12' };

  const title = isSuccess
    ? (fullyDone ? 'All Checked In!' : 'Checked In!')
    : isDuplicate ? 'Already Checked In' : 'Not Found';

  const pct = guest ? Math.round((guest.checked_in_count / guest.total_attendees) * 100) : 0;

  const nextNum = guest ? guest.checked_in_count + 1 : 0;

  return (
    <div className="absolute inset-0 z-20 flex items-end justify-center pb-4 bg-black/65 backdrop-blur-sm">

      {/* ── Card ──────────────────────────────────────────────────────────── */}
      <div className={`w-full max-w-sm mx-4 bg-white rounded-3xl shadow-2xl ${theme.shadow} overflow-hidden animate-slide-up`}>

        {/* ── Header band ───────────────────────────────────────────────── */}
        <div className={`${theme.band} px-6 pt-6 pb-8 flex items-center gap-4`}>
          {/* Icon circle */}
          <div className={`
            shrink-0 w-14 h-14 rounded-2xl bg-white/20 flex items-center justify-center
            ${isSuccess ? 'animate-success-pop' : ''}
          `}>
            <svg className="w-7 h-7 text-white" fill="none" stroke="currentColor" strokeWidth={2.5} viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" d={theme.icon} />
            </svg>
          </div>

          {/* Title + sub-status */}
          <div className="min-w-0">
            <h2 className="text-white text-xl font-extrabold leading-tight tracking-tight">{title}</h2>
            {keepOpen && guest && (
              <p className="text-white/80 text-sm mt-0.5 font-medium">
                Person {guest.checked_in_count} of {guest.total_attendees} done
              </p>
            )}
            {fullyDone && guest && isMulti(guest) && (
              <p className="text-white/80 text-sm mt-0.5 font-medium">
                All {guest.total_attendees} attendees in
              </p>
            )}
            {isDuplicate && guest && (
              <p className="text-white/80 text-sm mt-0.5 font-medium truncate">{guest.name}</p>
            )}
          </div>
        </div>

        {/* ── Curved join ──────────────────────────────────────────────── */}
        <div className={`${theme.band} h-4 relative`}>
          <div className="absolute inset-x-0 bottom-0 h-4 bg-white rounded-t-[1.75rem]" />
        </div>

        {/* ── Body ──────────────────────────────────────────────────────── */}
        <div className="bg-white px-5 pt-1 pb-5 -mt-0.5">

          {guest && (
            <>
              {/* Card thumbnail */}
              {guest.generated_card_url && (
                <div className="mb-3">
                  <img
                    src={guest.generated_card_url}
                    alt=""
                    className="w-full h-24 object-cover rounded-2xl shadow-sm"
                    onError={e => { (e.currentTarget as HTMLImageElement).style.display = 'none'; }}
                  />
                </div>
              )}

              {/* Name + card info */}
              <div className="mb-3">
                <p className="text-slate-900 text-lg font-extrabold leading-tight truncate">{guest.name}</p>
                <div className="flex items-center gap-2 mt-1 flex-wrap">
                  <span className={`text-xs font-semibold px-2 py-0.5 rounded-full text-white ${theme.pill}`}>
                    {cardTypeLabel(guest.card_type)}
                  </span>
                  <span className="text-xs text-slate-400 font-medium">Card #{guest.card_number ?? '—'}</span>
                  {guest.checked_in_at && (
                    <span className="text-xs text-slate-400 font-medium">{formatTime(guest.checked_in_at)}</span>
                  )}
                </div>
              </div>

              {/* Progress bar */}
              <div className="mb-4">
                <div className="flex items-center justify-between mb-1.5">
                  <span className="text-xs font-semibold text-slate-500 uppercase tracking-wide">Attendees</span>
                  <span className="text-xs font-bold text-slate-700">
                    {guest.checked_in_count}/{guest.total_attendees}
                    {isDone(guest) && <span className="text-emerald-600 ml-1">✓</span>}
                  </span>
                </div>
                <div className="h-2 bg-slate-100 rounded-full overflow-hidden">
                  <div
                    className={`h-full rounded-full transition-all duration-500 ${theme.bar}`}
                    style={{ width: `${pct}%` }}
                  />
                </div>

                {/* Seat dots for small groups */}
                {guest.total_attendees <= 6 && (
                  <div className="flex gap-1.5 mt-2 justify-center">
                    {Array.from({ length: guest.total_attendees }).map((_, i) => (
                      <div
                        key={i}
                        className={`flex-1 h-1.5 rounded-full transition-all duration-300 ${
                          i < guest.checked_in_count ? theme.bar : 'bg-slate-100'
                        }`}
                      />
                    ))}
                  </div>
                )}
              </div>
            </>
          )}

          {/* Error message */}
          {!guest && message && (
            <p className="text-center text-slate-500 text-sm py-3 leading-relaxed">{message}</p>
          )}

          {/* ── Action buttons ──────────────────────────────────────────── */}
          <div className="flex flex-col gap-2.5">

            {keepOpen && (
              /* ── Primary: check in next person ── */
              <button
                onClick={onNextAttendee}
                disabled={isProcessing}
                className={`
                  w-full py-4 rounded-2xl font-bold text-[15px] text-white
                  flex items-center justify-center gap-2.5
                  active:scale-95 transition-all duration-150
                  disabled:opacity-60 disabled:cursor-not-allowed
                  ${theme.band} shadow-lg ${theme.shadow}
                `}
              >
                {isProcessing ? (
                  <>
                    <svg className="w-5 h-5 animate-spin shrink-0" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"/>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"/>
                    </svg>
                    <span>Checking in…</span>
                  </>
                ) : (
                  <>
                    <svg className="w-5 h-5 shrink-0" fill="none" stroke="currentColor" strokeWidth={2.5} viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3" />
                    </svg>
                    <span>Next Attendee</span>
                    <span className="bg-white/25 text-white text-xs font-bold px-2 py-0.5 rounded-full">
                      {nextNum}/{guest?.total_attendees}
                    </span>
                  </>
                )}
              </button>
            )}

            {/* Secondary / only button */}
            <button
              onClick={onDismiss}
              disabled={isProcessing}
              className={`
                w-full rounded-2xl font-semibold text-sm transition-all active:scale-95
                disabled:opacity-40
                ${keepOpen
                  ? 'py-3 text-slate-400 hover:text-slate-600'
                  : 'py-3.5 bg-slate-100 text-slate-600'
                }
              `}
            >
              {keepOpen ? 'Done — Close' : 'Tap to dismiss'}
            </button>

          </div>
        </div>
      </div>
    </div>
  );
}
