import React, { forwardRef, useEffect, useImperativeHandle } from 'react'
import { FieldErrors, useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import { Label, Select, Badge, Alert } from 'flowbite-react'
import { LuCircleAlert } from 'react-icons/lu'

import { ActivityProduct } from '@/lib/types/product/activity'
import DatePicker, { FormattedDate } from '@/lib/components/DatePicker'
import Counter from '@/lib/components/Counter'
import formTheme from '@/lib/themes/form'
import badgeTheme from '@/lib/themes/badge'
import { getKualaLumpurDate, parseKualaLumpurDate } from '@/lib/utils/date'

export const MINIMUM_DATE = getKualaLumpurDate(new Date(), true)

// Import existing schemas and types from experience-orders
export interface ActivityBookingFormData {
  category: 'tour' | 'activity'
  booking_date: Date
  visit_time?: string
  adult_participant: {
    domestic: number
    foreigner: number
  }
  child_participant: {
    domestic: number
    foreigner: number
  }
}

import * as yup from 'yup'

export const activityBookingFormSchema: yup.ObjectSchema<ActivityBookingFormData> =
  yup.object({
    category: yup.string().oneOf(['tour', 'activity']).required(),
    booking_date: yup
      .date()
      .required('Booking date is required')
      .min(
        getKualaLumpurDate(new Date(), true),
        'Booking date must at least equal to Today',
      ),
    visit_time: yup.string().when('category', {
      is: 'activity',
      then: (schema) => schema.required('Please select a visit time'),
      otherwise: (schema) => schema.optional(),
    }),
    adult_participant: yup
      .object({
        domestic: yup.number().integer().min(0).required(),
        foreigner: yup.number().integer().min(0).required(),
      })
      .test(
        'at-least-one-adult',
        'At least one adult participant is required',
        function (value) {
          return value.domestic > 0 || value.foreigner > 0
        },
      ),
    child_participant: yup.object({
      domestic: yup.number().integer().min(0).required(),
      foreigner: yup.number().integer().min(0).required(),
    }),
  })

export interface ActivityBookingFormRef {
  getValues: () => ActivityBookingFormData
  validateForm: () => Promise<boolean>
  formState: {
    isValid: boolean
    errors: FieldErrors<ActivityBookingFormData>
  }
}

interface ActivityBookingFormWrapperProps {
  activityProduct: ActivityProduct
  initialData?: ActivityBookingFormData
  onValidationChange?: (isValid: boolean) => void
  onDataChange?: (data: ActivityBookingFormData) => void
}

const ActivityBookingFormWrapper = forwardRef<
  ActivityBookingFormRef,
  ActivityBookingFormWrapperProps
>(({ onValidationChange, ...props }, ref) => {
  const {
    formState: { errors, isValid },
    register,
    setValue,
    watch,
    getValues,
    trigger,
  } = useForm<ActivityBookingFormData>({
    resolver: yupResolver(activityBookingFormSchema),
    mode: 'onChange',
    defaultValues: {
      category: props.initialData?.category ?? props.activityProduct.category,
      booking_date: props.initialData?.booking_date ?? MINIMUM_DATE,
      visit_time: props.initialData?.visit_time ?? '',
      adult_participant: {
        domestic: props.initialData?.adult_participant?.domestic ?? 0,
        foreigner: props.initialData?.adult_participant?.foreigner ?? 0,
      },
      child_participant: {
        domestic: props.initialData?.child_participant?.domestic ?? 0,
        foreigner: props.initialData?.child_participant?.foreigner ?? 0,
      },
    },
  })

  const watchedValues = watch()
  const totalParticipant =
    watchedValues.adult_participant.domestic +
    watchedValues.adult_participant.foreigner +
    watchedValues.child_participant.domestic +
    watchedValues.child_participant.foreigner

  // Expose form state and methods through ref
  useImperativeHandle(ref, () => ({
    formState: {
      isValid: isValid && totalParticipant >= props.activityProduct.min_pax,
      errors,
    },
    getValues,
    validateForm: async () => {
      const result = await trigger()
      return result && totalParticipant >= props.activityProduct.min_pax
    },
  }))

  // Notify parent of validation changes
  useEffect(() => {
    const formIsValid =
      isValid && totalParticipant >= props.activityProduct.min_pax

    onValidationChange?.(formIsValid)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isValid, totalParticipant])

  const handleBookingDateChange = (formattedDate: FormattedDate) => {
    if (formattedDate.startDate) {
      setValue('booking_date', parseKualaLumpurDate(formattedDate.startDate))
      trigger('booking_date')

      props.onDataChange?.({
        ...watchedValues,
        booking_date: parseKualaLumpurDate(formattedDate.startDate),
      })
    } else {
      setValue('booking_date', MINIMUM_DATE)
      trigger('booking_date')

      props.onDataChange?.({
        ...watchedValues,
        booking_date: MINIMUM_DATE,
      })
    }
  }

  const handleVisitTimeChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setValue('visit_time', e.target.value)
    trigger('visit_time')

    props.onDataChange?.({
      ...watchedValues,
      visit_time: e.target.value,
    })
  }

  const handleParticipantChange = (
    category: 'adult' | 'child',
    nationality: 'domestic' | 'foreigner',
    value: number,
  ) => {
    setValue(`${category}_participant.${nationality}`, value)
    trigger(`${category}_participant`)

    props.onDataChange?.({
      ...watchedValues,
      [`${category}_participant`]: {
        ...watchedValues[`${category}_participant`],
        [nationality]: value,
      },
    })
  }

  return (
    <div className="space-y-4">
      <div className="space-y-8">
        {/* Booking Date */}
        <div>
          <div className="mb-2">
            <Label htmlFor="booking_date" theme={formTheme.label}>
              Booking Date
            </Label>
          </div>

          <DatePicker
            inputId="booking_date"
            asSingle={true}
            minDate={MINIMUM_DATE}
            onDateChange={handleBookingDateChange}
            value={{
              startDate: watchedValues.booking_date,
              endDate: watchedValues.booking_date,
            }}
          />
          {errors.booking_date && (
            <p className="mt-1 text-sm text-red-600">
              {errors.booking_date.message?.toString()}
            </p>
          )}
        </div>

        {/* Visit Time for Activity */}
        {props.activityProduct.category === 'activity' && (
          <div>
            <div className="mb-2">
              <Label htmlFor="visit_time" className="mb-2">
                Visit Time
              </Label>
            </div>

            <Select
              {...register('visit_time')}
              theme={formTheme.select}
              id="visit_time"
              onChange={handleVisitTimeChange}
            >
              <option value="">Select visit time</option>
              {props.activityProduct.time_slots?.map((timeSlot) => (
                <option key={timeSlot.id} value={timeSlot.time}>
                  {timeSlot.time}
                </option>
              ))}
            </Select>
            {errors.visit_time && (
              <p className="mt-1 text-sm text-red-600">
                {errors.visit_time.message?.toString()}
              </p>
            )}
          </div>
        )}

        {/* Participants - Compact Layout */}
        <div className="space-y-4">
          <Alert color="blue" icon={LuCircleAlert} className="text-sm">
            The minimum number of {props.activityProduct.min_pax} participants
            are required and should include at least one adult.
          </Alert>

          {/* Foreigner Participants */}
          <div>
            <Badge
              color="gray"
              theme={badgeTheme.badge}
              size="xs"
              className="mb-2 w-fit"
            >
              FOREIGNER PARTICIPANT
            </Badge>

            <div className="flex sm:space-x-4 flex-wrap sm:flex-nowrap gap-4">
              <div className="w-full">
                <Label htmlFor="adult_foreigner" className="text-sm">
                  Adult
                </Label>
                <Counter
                  value={watchedValues.adult_participant.foreigner}
                  onChange={(value) => {
                    handleParticipantChange('adult', 'foreigner', value)
                  }}
                  className="mt-1"
                />
              </div>

              {props.activityProduct.is_support_child && (
                <div className="w-full">
                  <Label htmlFor="child_foreigner" className="text-sm">
                    Child
                  </Label>
                  <Counter
                    value={watchedValues.child_participant.foreigner}
                    onChange={(value) => {
                      handleParticipantChange('child', 'foreigner', value)
                    }}
                    className="mt-1"
                  />
                </div>
              )}
            </div>
          </div>

          {/* Domestic Participants */}
          <div>
            <Badge
              theme={badgeTheme.badge}
              color="gray"
              size="xs"
              className="mb-2 w-fit"
            >
              DOMESTIC PARTICIPANT
            </Badge>

            <div className="flex sm:space-x-4 flex-wrap sm:flex-nowrap gap-4">
              <div className="w-full">
                <Label htmlFor="adult_domestic" className="text-sm">
                  Adult
                </Label>
                <Counter
                  value={watchedValues.adult_participant.domestic}
                  onChange={(value) => {
                    handleParticipantChange('adult', 'domestic', value)
                  }}
                  className="mt-1"
                />
              </div>

              {props.activityProduct.is_support_child && (
                <div className="w-full">
                  <Label htmlFor="child_domestic" className="text-sm">
                    Child
                  </Label>
                  <Counter
                    value={watchedValues.child_participant.domestic}
                    onChange={(value) => {
                      handleParticipantChange('child', 'domestic', value)
                    }}
                    className="mt-1"
                  />
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
})

ActivityBookingFormWrapper.displayName = 'ActivityBookingFormWrapper'

export default ActivityBookingFormWrapper
