'use client';

import { useState, useEffect, useRef } from 'react';
import { UserPlusIcon, ChevronDownIcon } from '@heroicons/react/24/outline';
import clsx from 'clsx';
import type { DoorPaymentMethod } from '@/lib/api';
import { PaymentButtons } from './PaymentButtons';

export interface WalkInDraft {
  firstName: string;
  lastName: string;
  phone: string;
  email: string;
  ruc: string;
}

export const emptyWalkIn = (firstName = ''): WalkInDraft => ({
  firstName,
  lastName: '',
  phone: '',
  email: '',
  ruc: '',
});

/**
 * The pinned bottom row. Collapsed it is a single tap; expanded it is a first
 * name and four tenders. Email, phone and RUC live behind "Add details" so the
 * rare person who wants a receipt never slows down the queue behind them.
 */
export function WalkInRow({
  typedText,
  expanded,
  draft,
  price,
  currency,
  busy,
  onExpand,
  onChange,
  onPay,
  onCancel,
}: {
  typedText: string;
  expanded: boolean;
  draft: WalkInDraft;
  price: number;
  currency: string;
  busy: boolean;
  onExpand: () => void;
  onChange: (draft: WalkInDraft) => void;
  onPay: (method: DoorPaymentMethod, amount: number) => void;
  onCancel: () => void;
}) {
  const [detailsOpen, setDetailsOpen] = useState(false);
  const firstNameRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (expanded) firstNameRef.current?.focus();
  }, [expanded]);

  useEffect(() => {
    if (!expanded) setDetailsOpen(false);
  }, [expanded]);

  if (!expanded) {
    return (
      <button
        onClick={onExpand}
        className="w-full min-h-[64px] px-4 py-3 rounded-2xl border-2 border-dashed border-primary-yellow/50 bg-primary-yellow/5 text-left flex items-center gap-3 active:scale-[0.99] transition-transform"
      >
        <UserPlusIcon className="w-6 h-6 text-primary-yellow flex-shrink-0" />
        <span className="font-bold text-primary-yellow truncate">
          {typedText ? `Add "${typedText}" as walk-in` : 'Add a walk-in'}
        </span>
      </button>
    );
  }

  const field = (key: keyof WalkInDraft, value: string) => onChange({ ...draft, [key]: value });

  return (
    <div className="rounded-2xl border-2 border-primary-yellow/50 bg-gray-800 p-3 space-y-2">
      <div className="flex items-center justify-between px-1">
        <p className="font-bold text-primary-yellow">New walk-in</p>
        <button onClick={onCancel} className="text-sm text-gray-400 min-h-[48px] px-2 active:text-white">
          Cancel
        </button>
      </div>

      <div className="grid grid-cols-2 gap-2">
        <input
          ref={firstNameRef}
          value={draft.firstName}
          onChange={(e) => field('firstName', e.target.value)}
          placeholder="First name"
          autoComplete="off"
          autoCorrect="off"
          spellCheck={false}
          className="min-h-[48px] px-4 bg-gray-900 border border-gray-700 rounded-xl text-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-yellow"
        />
        <input
          value={draft.lastName}
          onChange={(e) => field('lastName', e.target.value)}
          placeholder="Last name (optional)"
          autoComplete="off"
          autoCorrect="off"
          spellCheck={false}
          className="min-h-[48px] px-4 bg-gray-900 border border-gray-700 rounded-xl text-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-yellow"
        />
      </div>

      <input
        value={draft.phone}
        onChange={(e) => field('phone', e.target.value)}
        placeholder="Phone (optional)"
        inputMode="tel"
        autoComplete="off"
        className="w-full min-h-[48px] px-4 bg-gray-900 border border-gray-700 rounded-xl text-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-yellow"
      />

      <button
        onClick={() => setDetailsOpen((open) => !open)}
        className="w-full min-h-[48px] flex items-center justify-between px-2 text-sm text-gray-400 active:text-white"
      >
        Add details (email, RUC)
        <ChevronDownIcon className={clsx('w-4 h-4 transition-transform', detailsOpen && 'rotate-180')} />
      </button>

      {detailsOpen && (
        <div className="space-y-2">
          <input
            value={draft.email}
            onChange={(e) => field('email', e.target.value)}
            placeholder="Email — sends the usual confirmation"
            inputMode="email"
            autoComplete="off"
            autoCapitalize="none"
            className="w-full min-h-[48px] px-4 bg-gray-900 border border-gray-700 rounded-xl text-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-yellow"
          />
          <input
            value={draft.ruc}
            onChange={(e) => field('ruc', e.target.value)}
            placeholder="RUC (for factura)"
            autoComplete="off"
            className="w-full min-h-[48px] px-4 bg-gray-900 border border-gray-700 rounded-xl text-white placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-primary-yellow"
          />
        </div>
      )}

      <PaymentButtons
        price={price}
        currency={currency}
        onPay={onPay}
        disabled={busy || !draft.firstName.trim()}
      />
    </div>
  );
}
