import Link from 'next/link';
import Card from '@/components/ui/Card';
import Button from '@/components/ui/Button';
import Input from '@/components/ui/Input';
import {
  CalendarIcon,
  MapPinIcon,
  UserGroupIcon,
  CurrencyDollarIcon,
  ArrowLeftIcon,
  CheckCircleIcon,
  UserIcon,
} from '@heroicons/react/24/outline';
import { Event } from '@/lib/api';
import { formatPrice } from '@/lib/utils';
import type { AttendeeInfo, BookingFormData } from '../_types';
import type { PaymentMethodOption } from '../_logic/booking';

interface BookingFormStepProps {
  event: Event;
  locale: string;
  t: (key: string) => string;
  spotsLeft: number;
  isSoldOut: boolean;
  ticketQuantity: number;
  formData: BookingFormData;
  setFormData: React.Dispatch<React.SetStateAction<BookingFormData>>;
  errors: Partial<Record<keyof BookingFormData, string>>;
  attendees: AttendeeInfo[];
  setAttendees: React.Dispatch<React.SetStateAction<AttendeeInfo[]>>;
  attendeeErrors: { [key: number]: string };
  setAttendeeErrors: React.Dispatch<React.SetStateAction<{ [key: number]: string }>>;
  handleRucChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  handleRucBlur: () => void;
  paymentMethods: PaymentMethodOption[];
  agreedToTerms: boolean;
  setAgreedToTerms: (value: boolean) => void;
  termsError: string | null;
  submitting: boolean;
  onSubmit: (e: React.FormEvent) => void;
  formatDate: (dateStr: string) => string;
  fmtTime: (dateStr: string) => string;
}

export function BookingFormStep({
  event,
  locale,
  t,
  spotsLeft,
  isSoldOut,
  ticketQuantity,
  formData,
  setFormData,
  errors,
  attendees,
  setAttendees,
  attendeeErrors,
  setAttendeeErrors,
  handleRucChange,
  handleRucBlur,
  paymentMethods,
  agreedToTerms,
  setAgreedToTerms,
  termsError,
  submitting,
  onSubmit,
  formatDate,
  fmtTime,
}: BookingFormStepProps) {
  return (
    <div className="section-padding bg-secondary-gray min-h-screen">
      <div className="container-page max-w-2xl">
        <Link
          href={`/events/${event.slug}`}
          className="inline-flex items-center gap-2 text-gray-600 hover:text-primary-dark mb-6"
        >
          <ArrowLeftIcon className="w-4 h-4" />
          {t('common.back')}
        </Link>

        {/* Event Summary - Always Visible */}
        <Card className="mb-6 overflow-hidden">
          <div className="bg-primary-yellow/20 p-4 border-b border-primary-yellow/30">
            <h2 className="font-bold text-lg text-primary-dark">
              {locale === 'es' && event.titleEs ? event.titleEs : event.title}
            </h2>
          </div>
          <div className="p-4 space-y-2 text-sm">
            <div className="flex items-center gap-3">
              <CalendarIcon className="w-5 h-5 text-primary-yellow" />
              <span>{formatDate(event.startDatetime)} • {fmtTime(event.startDatetime)}</span>
            </div>
            <div className="flex items-center gap-3">
              <MapPinIcon className="w-5 h-5 text-primary-yellow" />
              <span>{event.location}</span>
            </div>
            {!event.externalBookingEnabled && (
              <div className="flex items-center gap-3">
                <UserGroupIcon className="w-5 h-5 text-primary-yellow" />
                <span>{spotsLeft} / {event.capacity} {t('events.details.spotsLeft')}</span>
              </div>
            )}
            <div className="flex items-center gap-3">
              <CurrencyDollarIcon className="w-5 h-5 text-primary-yellow" />
              <span className="font-bold text-lg">
                {event.price === 0
                  ? t('events.details.free')
                  : formatPrice(event.price, event.currency)}
              </span>
              {event.price > 0 && (
                <span className="text-gray-400 text-sm">
                  {locale === 'es' ? 'por persona' : 'per person'}
                </span>
              )}
            </div>
            {/* Ticket quantity and total */}
            {ticketQuantity > 1 && (
              <div className="mt-3 pt-3 border-t border-secondary-light-gray">
                <div className="flex items-center justify-between">
                  <span className="text-gray-600">
                    {locale === 'es' ? 'Tickets' : 'Tickets'}: <span className="font-semibold">{ticketQuantity}</span>
                  </span>
                  <span className="font-bold text-lg text-primary-dark">
                    {locale === 'es' ? 'Total' : 'Total'}: {formatPrice(event.price * ticketQuantity, event.currency)}
                  </span>
                </div>
              </div>
            )}
          </div>
        </Card>

        {isSoldOut ? (
          <Card className="p-8 text-center">
            <UserGroupIcon className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <h2 className="text-xl font-bold text-gray-700">{t('events.details.soldOut')}</h2>
            <p className="text-gray-500 mt-2">{t('booking.form.soldOutMessage')}</p>
          </Card>
        ) : (
          <form onSubmit={onSubmit}>
            {/* User Information Section */}
            <Card className="mb-6 p-6">
              <h3 className="font-bold text-lg mb-4 text-primary-dark flex items-center gap-2">
                {attendees.length > 0 && (
                  <span className="w-6 h-6 rounded-full bg-primary-yellow text-primary-dark text-sm font-bold flex items-center justify-center">
                    1
                  </span>
                )}
                {t('booking.form.personalInfo')}
                {attendees.length > 0 && (
                  <span className="text-sm font-normal text-gray-500">
                    ({locale === 'es' ? 'Asistente principal' : 'Primary attendee'})
                  </span>
                )}
              </h3>

              <div className="space-y-4">
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <Input
                    label={t('booking.form.firstName')}
                    value={formData.firstName}
                    onChange={(e) => setFormData({ ...formData, firstName: e.target.value })}
                    placeholder={t('booking.form.firstNamePlaceholder')}
                    error={errors.firstName}
                    required
                  />
                  <div>
                    <div className="flex items-center gap-2 mb-1">
                      <label className="block text-sm font-medium text-gray-700">
                        {t('booking.form.lastName')}
                      </label>
                      <span className="text-xs text-gray-400">
                        ({locale === 'es' ? 'Opcional' : 'Optional'})
                      </span>
                    </div>
                    <Input
                      value={formData.lastName}
                      onChange={(e) => setFormData({ ...formData, lastName: e.target.value })}
                      placeholder={t('booking.form.lastNamePlaceholder')}
                      error={errors.lastName}
                    />
                  </div>
                </div>

                <div>
                  <Input
                    label={t('booking.form.email')}
                    type="email"
                    value={formData.email}
                    onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                    placeholder={t('booking.form.emailPlaceholder')}
                    error={errors.email}
                    required
                  />
                </div>

                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <label className="block text-sm font-medium text-gray-700">
                      {t('booking.form.phone')}
                    </label>
                    <span className="text-xs text-gray-400">
                      ({locale === 'es' ? 'Opcional' : 'Optional'})
                    </span>
                  </div>
                  <Input
                    type="tel"
                    value={formData.phone}
                    onChange={(e) => setFormData({ ...formData, phone: e.target.value })}
                    placeholder={t('booking.form.phonePlaceholder')}
                    error={errors.phone}
                  />
                </div>

                <div>
                  <div className="flex items-center gap-2 mb-1">
                    <label className="block text-sm font-medium text-gray-700">
                      {t('booking.form.ruc')}
                    </label>
                    <span className="text-xs text-gray-400">
                      {t('booking.form.rucOptional')}
                    </span>
                  </div>
                  <Input
                    value={formData.ruc}
                    onChange={handleRucChange}
                    onBlur={handleRucBlur}
                    placeholder={t('booking.form.rucPlaceholder')}
                    error={errors.ruc}
                    maxLength={10}
                    aria-label={t('booking.form.ruc')}
                  />
                </div>
              </div>
            </Card>

            {/* Additional Attendees Section (for multi-ticket bookings) */}
            {attendees.length > 0 && (
              <Card className="mb-6 p-6">
                <h3 className="font-bold text-lg mb-4 text-primary-dark flex items-center gap-2">
                  <UserIcon className="w-5 h-5 text-primary-yellow" />
                  {locale === 'es' ? 'Información de los Otros Asistentes' : 'Other Attendees Information'}
                </h3>
                <p className="text-sm text-gray-600 mb-4">
                  {locale === 'es'
                    ? 'Ingresa el nombre de cada asistente adicional. Cada persona recibirá su propio ticket.'
                    : 'Enter the name for each additional attendee. Each person will receive their own ticket.'}
                </p>

                <div className="space-y-4">
                  {attendees.map((attendee, index) => (
                    <div key={index} className="p-4 bg-gray-50 rounded-lg">
                      <div className="flex items-center gap-2 mb-3">
                        <span className="w-6 h-6 rounded-full bg-primary-yellow text-primary-dark text-sm font-bold flex items-center justify-center">
                          {index + 2}
                        </span>
                        <span className="font-medium text-gray-700">
                          {locale === 'es' ? `Asistente ${index + 2}` : `Attendee ${index + 2}`}
                        </span>
                      </div>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                        <Input
                          label={t('booking.form.firstName')}
                          value={attendee.firstName}
                          onChange={(e) => {
                            const newAttendees = [...attendees];
                            newAttendees[index].firstName = e.target.value;
                            setAttendees(newAttendees);
                            if (attendeeErrors[index]) {
                              const newErrors = { ...attendeeErrors };
                              delete newErrors[index];
                              setAttendeeErrors(newErrors);
                            }
                          }}
                          placeholder={t('booking.form.firstNamePlaceholder')}
                          error={attendeeErrors[index]}
                          required
                        />
                        <div>
                          <div className="flex items-center gap-2 mb-1">
                            <label className="block text-sm font-medium text-gray-700">
                              {t('booking.form.lastName')}
                            </label>
                            <span className="text-xs text-gray-400">
                              ({locale === 'es' ? 'Opcional' : 'Optional'})
                            </span>
                          </div>
                          <Input
                            value={attendee.lastName}
                            onChange={(e) => {
                              const newAttendees = [...attendees];
                              newAttendees[index].lastName = e.target.value;
                              setAttendees(newAttendees);
                            }}
                            placeholder={t('booking.form.lastNamePlaceholder')}
                          />
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </Card>
            )}

            {/* Payment Selection Section */}
            <Card className="mb-6 p-6">
              <h3 className="font-bold text-lg mb-4 text-primary-dark">
                {t('booking.form.paymentMethod')}
              </h3>

              <div className="space-y-3">
                {paymentMethods.length === 0 ? (
                  <div className="text-center py-8 text-gray-500">
                    {locale === 'es'
                      ? 'No hay métodos de pago disponibles para este evento.'
                      : 'No payment methods available for this event.'}
                  </div>
                ) : (
                  <>
                    {paymentMethods.map((method) => (
                      <button
                        key={method.id}
                        type="button"
                        onClick={() => setFormData((prev) => ({ ...prev, paymentMethod: method.id }))}
                        className={`w-full p-4 rounded-lg border-2 transition-all text-left flex items-start gap-4 ${
                          formData.paymentMethod === method.id
                            ? 'border-primary-yellow bg-primary-yellow/10'
                            : 'border-secondary-light-gray hover:border-gray-300'
                        }`}
                      >
                        <div className={`w-10 h-10 rounded-full flex items-center justify-center flex-shrink-0 ${
                          formData.paymentMethod === method.id
                            ? 'bg-primary-yellow'
                            : 'bg-gray-100'
                        }`}>
                          <method.icon className={`w-5 h-5 ${
                            formData.paymentMethod === method.id
                              ? 'text-primary-dark'
                              : 'text-gray-500'
                          }`} />
                        </div>
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <p className="font-medium text-primary-dark">{method.label}</p>
                            {method.badge && (
                              <span className={`text-xs px-2 py-0.5 rounded-full ${
                                method.badge === 'Instant' || method.badge === 'Instantáneo'
                                  ? 'bg-green-100 text-green-700'
                                  : 'bg-gray-100 text-gray-600'
                              }`}>
                                {method.badge}
                              </span>
                            )}
                          </div>
                          <p className="text-sm text-gray-500">{method.description}</p>
                        </div>
                        {formData.paymentMethod === method.id && (
                          <CheckCircleIcon className="w-6 h-6 text-primary-yellow ml-auto flex-shrink-0" />
                        )}
                      </button>
                    ))}

                  </>
                )}
              </div>
              {errors.paymentMethod && (
                <p className="mt-3 text-sm text-red-600">{errors.paymentMethod}</p>
              )}
            </Card>

            {/* Terms & Privacy agreement */}
            <Card className="mb-6 p-6">
              <div className="flex items-start gap-3">
                <input
                  id="booking-terms-agree"
                  type="checkbox"
                  checked={agreedToTerms}
                  onChange={(e) => setAgreedToTerms(e.target.checked)}
                  aria-required="true"
                  aria-invalid={termsError ? true : undefined}
                  aria-describedby={termsError ? 'booking-terms-error' : undefined}
                  className="h-5 w-5 mt-0.5 flex-shrink-0 accent-primary-yellow rounded focus:outline-none focus:ring-2 focus:ring-primary-yellow focus:ring-offset-2 cursor-pointer"
                />
                <label
                  htmlFor="booking-terms-agree"
                  className="text-sm text-gray-500 leading-relaxed cursor-pointer select-none"
                >
                  {t('booking.form.termsAgreePart1')}
                  <Link
                    href={`/legal/terms-policy${locale === 'es' ? '?locale=es' : ''}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-secondary-blue hover:text-brand-navy underline"
                  >
                    {t('booking.form.termsOfService')}
                  </Link>
                  {t('booking.form.termsAgreePart2')}
                  <Link
                    href={`/legal/privacy-policy${locale === 'es' ? '?locale=es' : ''}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-secondary-blue hover:text-brand-navy underline"
                  >
                    {t('booking.form.privacyPolicy')}
                  </Link>
                  {t('booking.form.termsAgreePart3')}
                </label>
              </div>
              {termsError && (
                <p id="booking-terms-error" className="mt-1.5 text-sm text-red-600">
                  {termsError}
                </p>
              )}
            </Card>

            {/* Submit Button */}
            <Button
              type="submit"
              size="lg"
              className="w-full"
              isLoading={submitting}
              disabled={paymentMethods.length === 0 || !formData.paymentMethod || !agreedToTerms}
            >
              {formData.paymentMethod === 'cash'
                ? t('booking.form.reserveSpot')
                : formData.paymentMethod === 'lightning'
                  ? t('booking.form.proceedPayment')
                  : locale === 'es' ? 'Continuar al Pago' : 'Continue to Payment'
              }
            </Button>
          </form>
        )}
      </div>
    </div>
  );
}
