import { useState } from 'react';
import clsx from 'clsx';
import { useCheckIn } from '../../hooks/useCheckIn';
import { useUIStore } from '../../store/uiStore';
import { Spinner } from '../ui/Spinner';
import { playCheckInSuccess } from '../../utils/audio';
import type { Guest } from '../../types/guest';

interface Props {
  guest: Guest;
  onSuccess?: (updated: Guest) => void;
}

export function CheckInButton({ guest, onSuccess }: Props) {
  const [loading, setLoading] = useState(false);
  const { handleManualCheckIn } = useCheckIn();
  const showToast = useUIStore(s => s.showToast);

  const isComplete = guest.checked_in_count >= guest.total_attendees;
  const isPartial  = guest.checked_in_count > 0 && !isComplete;

  const handleClick = async () => {
    if (isComplete || loading) return;
    setLoading(true);
    try {
      const result = await handleManualCheckIn(guest.id);
      if (result.status === 'checked_in' && result.guest) {
        playCheckInSuccess();
        showToast('success', result.message ?? 'Checked in!');
        onSuccess?.(result.guest);
      } else if (result.status === 'already_checked_in') {
        showToast('warning', 'Already checked in.');
      } else {
        showToast('error', 'Check-in failed. Please try again.');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <button
      onClick={handleClick}
      disabled={isComplete || loading}
      className={clsx(
        'flex items-center justify-center gap-2 w-full py-4 rounded-2xl text-base font-semibold transition-all active:scale-95',
        isComplete
          ? 'bg-emerald-50 text-emerald-600 border-2 border-emerald-200 cursor-default'
          : isPartial
          ? 'bg-secondary text-white shadow-lg active:shadow-md'
          : 'bg-primary text-white shadow-lg active:shadow-md'
      )}
    >
      {loading ? (
        <Spinner size="sm" className="text-white" />
      ) : isComplete ? (
        <>
          <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2.5} viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
          </svg>
          All Checked In
        </>
      ) : isPartial ? (
        <>
          <svg className="w-5 h-5" 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>
          Next Attendee ({guest.checked_in_count + 1}/{guest.total_attendees})
        </>
      ) : (
        <>
          <svg className="w-5 h-5" fill="none" stroke="currentColor" strokeWidth={2.5} viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          Check In ({guest.total_attendees > 1 ? `0/${guest.total_attendees}` : 'Guest'})
        </>
      )}
    </button>
  );
}
