import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import { format } from 'date-fns'
import { toast } from 'react-toastify'
import {
  LuShapes,
  LuShieldCheck,
  LuShip,
  LuShoppingCart,
  LuUser,
  LuUsers,
} from 'react-icons/lu'

import { AgentData } from '@/app/(dashboard)/agents/types'
import { ActivityProduct } from '@/lib/types/product/activity'
import {
  AggregatedFastboatProduct,
  FastboatProduct,
  FastboatRoute,
} from '@/lib/types/product/fastboat'
import {
  HarborTransferBanner,
  HarborTransferProduct,
} from '@/lib/types/product/harbor-transfer'
import { useMerchant } from '@/lib/context/MerchantContext'
import Stepper from '@/lib/components/stepper/Index'
import { scrollToRef } from '@/lib/utils/dom'
import { searchFastboatProducts } from '@/lib/services/fastboat-services'
import FullPageLoader from '@/lib/components/FullPageLoader'
import { parseKualaLumpurDate } from '@/lib/utils/date'
import PopupModal from '@/lib/components/modals/PopupModal'
import { usePopup } from '@/lib/hooks/usePopup'
import OrderBySelector from './OrderBySelector'
import { ServiceType } from './ServiceTypeSelector'
import {
  PassengerFormData,
  PassengerRate,
} from './boat-orders/passengers/types'
import BoatSearchForm from './boat-orders/boat-search-form'
import { boatSearchFormSchema } from './boat-orders/boat-search-form/schemas'
import { TransportDetailPayload, Trip, TripSegment } from './transports/types'
import FastBoatTicketCard from './boat-orders/boat-products/FastboatTicketCard'
import { adjustablePricesFormSchema } from './boat-orders/schemas'
import { passengerFormSchema } from './boat-orders/passengers/schemas'
import { createInitialPassengers } from './boat-orders/passengers/utils'
import Experience, { ExperienceState } from './experience-orders'
import ChooseBoat from './boat-orders/ChooseBoat'
import Transport from './boat-orders/Transport'
import PassengerDetail from './boat-orders/PassengerDetail'
import PriceManagementForm from './boat-orders/PriceManagementForm'
import * as activityOrderHelpers from './experience-orders/helpers'
import * as boatOrderHelpers from './boat-orders/helpers'
import * as transportOrderHelpers from './transports/helpers'
import { AxiosError } from 'axios'
import { HttpStatusCode } from '@/lib/types/enums/HttpStatusCode'
import {
  ActivityOrderPayload,
  CreateOrderPayload,
  FastboatOrderPayload,
} from '../types'
import OrderSummary from './billings/OrderSummary'
import BillingPaymentForm, {
  BillingPaymentFormRef,
} from './billings/BillingPaymentForm'
import { useCart } from '@/lib/context/CartContext'
import { BillingPaymentFormData } from './billings/schemas'
import BookingPolicies from './BookingPolicies'
import { createOrder } from '@/lib/services/order-services'
import { handleApiError } from '@/lib/utils/error-handler'
import { useRouter } from 'next/navigation'
import { Marketplace } from '@/app/(dashboard)/marketplaces/types'
import { AdjustablePriceFormData } from './boat-orders/types'

interface BoatBookingProps {
  onAddToCart: ({
    fastboatOrder,
    activityOrder,
    orderBy,
    agentId,
    marketplaceId,
  }: {
    fastboatOrder: FastboatOrderPayload
    activityOrder: ActivityOrderPayload | null
    orderBy: OrderByType
    agentId?: number
    marketplaceId?: number
  }) => void
  setSelectedServiceType: (type: ServiceType | null) => void
  countries: {
    isLoading: boolean
    data: Country[]
  }
  harborTransferBanner: {
    isLoading: boolean
    data: HarborTransferBanner | null
  }
  harborTransferProducts: {
    isLoading: boolean
    data: HarborTransferProduct[]
  }
  activityProducts: {
    isLoading: boolean
    data: ActivityProduct[]
  }
  fastboatRoutes: {
    isLoading: boolean
    data: FastboatRoute[]
  }
  agents: {
    isLoading: boolean
    data: AgentData[]
  }
  marketplaces: {
    isLoading: boolean
    data: Marketplace[]
  }
}

enum MasterStep {
  OrderPlacedBy = 0,
  ChooseBoats = 1,
  PassengerDetails = 2,
  OrderCompletion = 3,
}

enum ChooseBoatStep {
  ChooseDeparture = 0,
  ChooseReturn = 1,
  TransportServiceOffering = 2,
}

const DEFAULT_PASSENGER_RATE: Partial<PassengerRate> = {
  adult: {
    net_rate: 0,
    price: 0,
    agent_rate: 0,
    category: 'adult',
    strike_through_price: 0,
  },
  child: {
    net_rate: 0,
    price: 0,
    agent_rate: 0,
    category: 'child',
    strike_through_price: 0,
  },
  infant: {
    net_rate: 0,
    price: 0,
    agent_rate: 0,
    category: 'infant',
    strike_through_price: 0,
  },
}

const INITIAL_STEP = 0
const TOTAL_MASTER_STEPS = 4

export default function BoatBooking(props: BoatBookingProps) {
  const { merchant } = useMerchant()
  const {
    addFastboatToCart,
    prepareCartForCheckout,
    clearCart,
    updateCart,
    cart,
  } = useCart()
  const { popup, showPopup, hidePopup } = usePopup()
  const router = useRouter()
  const [selectedAgent, setSelectedAgent] = useState<AgentData | null>(null)
  const [selectedMarketplace, setSelectedMarketplace] =
    useState<Marketplace | null>(null)
  const [selectedOrderBy, setSelectedOrderBy] = useState<OrderByType | null>(
    null,
  )
  const [processing, setProcessing] = useState(false)

  // Refs
  const mainContentRef = useRef<HTMLDivElement>(null)
  const departureProductRef = useRef<HTMLDivElement>(null)
  const returnProductRef = useRef<HTMLDivElement>(null)
  const transportRef = useRef<HTMLDivElement>(null)
  const passengerDetailRef = useRef<HTMLDivElement>(null)
  const billingFormRef = useRef<BillingPaymentFormRef>(null)

  // Forms
  const searchForm = useForm({
    resolver: yupResolver(boatSearchFormSchema),
    defaultValues: {
      departureDate: format(new Date(), 'yyyy-MM-dd'),
      returnDate: format(new Date(), 'yyyy-MM-dd'),
      trip: Trip.ONE_WAY,
      selectedDeparture: {
        harbor: '',
        island: '',
        type: 'direct' as const,
      },
      selectedArrival: {
        harbor: '',
        island: '',
        type: 'direct' as const,
      },
      passengerCount: {
        adult: 1,
        child: 0,
        infant: 0,
      },
    },
  })
  const boatPriceForm = useForm<AdjustablePriceFormData>({
    resolver: yupResolver(adjustablePricesFormSchema),
    mode: 'onChange',
    defaultValues: {
      departurePrices: [],
      returnPrices: [],
    },
  })
  const passengerForm = useForm<PassengerFormData>({
    resolver: yupResolver(passengerFormSchema),
    mode: 'all',
    reValidateMode: 'onChange',
    defaultValues: {
      departurePassengers: createInitialPassengers({
        passengerCount: {
          adult: searchForm.getValues('passengerCount.adult'),
          child: searchForm.getValues('passengerCount.child'),
          infant: searchForm.getValues('passengerCount.infant'),
        },
        passengerRate: {
          adult: DEFAULT_PASSENGER_RATE.adult,
          child: DEFAULT_PASSENGER_RATE.child,
          infant: DEFAULT_PASSENGER_RATE.infant,
        },
      }),
      returnPassengers: [],
    },
  })

  // Transport States
  const [includeTransport, setIncludeTransport] = useState(false)
  const [transportDetailPayload, setTransportDetailPayload] =
    useState<TransportDetailPayload>({
      departure_pickup: null,
      departure_dropoff: null,
      return_pickup: null,
      return_dropoff: null,
    })

  // Boat States
  const [loadingBoats, setLoadingBoats] = useState(false)
  const [selectedDepartureProduct, setSelectedDepartureProduct] =
    useState<FastboatProduct | null>(null)
  const [selectedReturnProduct, setSelectedReturnProduct] =
    useState<FastboatProduct | null>(null)
  const [boatFound, setBoatFound] = useState(false)
  const [samePassenger, setSamePassenger] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const [aggregatedFastboatProducts, setAggregatedFastboatProducts] = useState<{
    departures: AggregatedFastboatProduct[]
    returns: AggregatedFastboatProduct[]
  }>({
    departures: [],
    returns: [],
  })
  const adultDepartureRate = selectedDepartureProduct?.prices?.find(
    (price) => price.category === 'adult',
  )
  const childDepartureRate = selectedDepartureProduct?.prices?.find(
    (price) => price.category === 'child',
  )
  const infantDepartureRate = selectedDepartureProduct?.prices?.find(
    (price) => price.category === 'infant',
  )
  const adultReturnRate = selectedReturnProduct?.prices?.find(
    (price) => price.category === 'adult',
  )
  const childReturnRate = selectedReturnProduct?.prices?.find(
    (price) => price.category === 'child',
  )
  const infantReturnRate = selectedReturnProduct?.prices?.find(
    (price) => price.category === 'infant',
  )
  const [matchedRoute, setMatchedRoute] = useState<FastboatRoute | null>(null)
  const chooseBoatSteps = [
    {
      step: 'Choose Departure',
      content: (
        <div ref={departureProductRef}>
          <h3 className="text-2xl font-semibold mb-4 bg-gradient-to-r from-blue-600 to-teal-500 text-transparent bg-clip-text">
            Departure,{' '}
            {searchForm?.getValues('departureDate') &&
              format(
                parseKualaLumpurDate(searchForm?.getValues('departureDate')),
                'dd MMM yyyy',
              )}
          </h3>

          <div className="space-y-4">
            {aggregatedFastboatProducts.departures?.map((departureProduct) => (
              <FastBoatTicketCard
                key={departureProduct.fastboat.id}
                product={departureProduct.fastboat}
                status={departureProduct.status}
                reviews={departureProduct.reviews}
                reviewCount={departureProduct.reviewCount}
                onSelect={(product) => handleSelectDeparture(product)}
                searchDepartureDate={searchForm.getValues('departureDate')}
                searchReturnDate={
                  searchForm.getValues('returnDate') ??
                  searchForm.getValues('departureDate')
                }
              />
            ))}
          </div>
        </div>
      ),
    },
    {
      step: 'Choose Return',
      content: (
        <div ref={returnProductRef}>
          <h3 className="text-2xl font-semibold mb-4 bg-gradient-to-r from-blue-600 to-teal-500 text-transparent bg-clip-text">
            Return,{' '}
            {searchForm?.getValues('returnDate') &&
              format(
                parseKualaLumpurDate(searchForm?.getValues('returnDate')),
                'dd MMM yyyy',
              )}
          </h3>

          <div className="space-y-4">
            {aggregatedFastboatProducts.returns?.map((returnProduct) => (
              <FastBoatTicketCard
                key={returnProduct.fastboat.id}
                onSelect={(product) => handleSelectReturn(product)}
                product={returnProduct.fastboat}
                status={returnProduct.status}
                reviews={returnProduct.reviews}
                reviewCount={returnProduct.reviewCount}
                searchDepartureDate={searchForm.getValues('departureDate')}
                searchReturnDate={
                  searchForm.getValues('returnDate') ??
                  searchForm.getValues('departureDate')
                }
              />
            ))}
          </div>
        </div>
      ),
    },
    {
      step: 'Transport Service Offering',
      content: (
        <Transport
          ref={transportRef}
          orderBy={selectedOrderBy}
          fastboatRoute={matchedRoute}
          includeTransport={includeTransport}
          departureProduct={selectedDepartureProduct}
          selectedAgent={selectedAgent}
          totalPax={
            searchForm.getValues('passengerCount.adult') +
            searchForm.getValues('passengerCount.child')
          }
          returnProduct={selectedReturnProduct}
          transportDetailPayload={transportDetailPayload}
          harborTransferBanner={props.harborTransferBanner.data}
          harborTransferProducts={props.harborTransferProducts.data}
          handleChangeMasterStep={handleChangeMasterStep}
          setIncludeTransport={setIncludeTransport}
          setTransportDetailPayload={setTransportDetailPayload}
        />
      ),
    },
  ]

  // Validation and Error States
  const [validationErrors, setValidationErrors] = useState<{
    [key: number]: string[]
  }>({})

  // Step States
  const [disabledNext, setDisabledNext] = useState(false)
  const [currentMasterStep, setCurrentMasterStep] = useState(INITIAL_STEP)
  const stepLabels = [
    'Order Placed By',
    'Choose Boats',
    'Passenger Details',
    selectedOrderBy === 'merchant' || selectedOrderBy === 'marketplace'
      ? 'Billing Details'
      : 'Experience',
  ]
  const stepIcons = [
    <LuUser key="order-placed-by" className="h-5 w-5" />,
    <LuShip key="choose-boats" className="h-5 w-5" />,
    <LuUsers key="passenger-details" className="h-5 w-5" />,
    selectedOrderBy === 'merchant' || selectedOrderBy === 'marketplace' ? (
      <LuShieldCheck key="billing-details" className="h-5 w-5" />
    ) : (
      <LuShapes key="experience" className="h-5 w-5" />
    ),
  ]
  const [currentChooseBoatStep, setCurrentChooseBoatStep] =
    useState(INITIAL_STEP)

  // Experience States
  const [experienceState, setExperienceState] = useState<ExperienceState>({
    includeExperience: false,
    selectedProduct: null,
    adjustablePrices: [],
    bookingData: null,
    isFormValid: false,
  })

  // Billing & Payment States
  const [isBillingPaymentValid, setIsBillingPaymentValid] = useState(false)
  const [billingPaymentState, setBillingPaymentState] = useState<
    Partial<BillingPaymentFormData>
  >({
    billingName: '',
    billingPhone: '',
    billingEmail: '',
    bookingSource: '',
  })

  // Booking Policies States
  const [refundable, setRefundable] = useState(true)
  const [reschedulable, setReschedulable] = useState(true)

  const getChooseBoatsValidationErrors = useCallback((): string[] => {
    const errors: string[] = []
    const trip = searchForm.getValues('trip')

    if (trip === 'ONE_WAY') {
      if (!selectedDepartureProduct) {
        errors.push('Please select a departure boat')
      } else if (includeTransport) {
        if (
          !transportDetailPayload.departure_pickup &&
          !transportDetailPayload.departure_dropoff
        ) {
          errors.push(
            'Please select either pickup or drop-off service for departure',
          )
        }
      }
    }

    if (trip === 'RETURN') {
      if (!selectedDepartureProduct) {
        errors.push('Please select a departure boat')
      }
      if (!selectedReturnProduct) {
        errors.push('Please select a return boat')
      }

      if (
        selectedDepartureProduct &&
        selectedReturnProduct &&
        includeTransport
      ) {
        const hasDepartureTransport = !!(
          transportDetailPayload.departure_pickup ||
          transportDetailPayload.departure_dropoff
        )
        const hasReturnTransport = !!(
          transportDetailPayload.return_pickup ||
          transportDetailPayload.return_dropoff
        )

        if (!hasDepartureTransport && !hasReturnTransport) {
          errors.push(
            'Please select pickup or drop-off service for at least one trip segment',
          )
        }
      }
    }

    return errors
  }, [
    includeTransport,
    searchForm,
    selectedDepartureProduct,
    selectedReturnProduct,
    transportDetailPayload.departure_dropoff,
    transportDetailPayload.departure_pickup,
    transportDetailPayload.return_dropoff,
    transportDetailPayload.return_pickup,
  ])

  const getStepValidationErrors = useCallback(
    (step: MasterStep): string[] => {
      const errors: string[] = []

      switch (step) {
        case MasterStep.OrderPlacedBy:
          if (!selectedOrderBy) {
            errors.push('Please select who is placing the order')
          }
          if (selectedOrderBy === 'agent' && !selectedAgent) {
            errors.push('Please select an agent.')
          }
          break

        case MasterStep.ChooseBoats:
          errors.push(...getChooseBoatsValidationErrors())
          break
      }

      return errors
    },
    [getChooseBoatsValidationErrors, selectedAgent, selectedOrderBy],
  )

  /**
   * Get React Hook Form errors for form-based steps
   */
  const getFormErrors = useCallback(
    (step: MasterStep): boolean => {
      switch (step) {
        case MasterStep.PassengerDetails:
          return (
            Object.keys(passengerForm.formState.errors).length > 0 ||
            Object.keys(boatPriceForm.formState.errors).length > 0
          )
        case MasterStep.OrderCompletion:
          if (
            selectedOrderBy === 'merchant' ||
            selectedOrderBy === 'marketplace'
          ) {
            return !isBillingPaymentValid
          }

          return (
            (experienceState.includeExperience &&
              experienceState.selectedProduct === null) ||
            (experienceState.selectedProduct !== null &&
              !experienceState.isFormValid)
          )
        default:
          return false
      }
    },
    [
      isBillingPaymentValid,
      selectedOrderBy,
      boatPriceForm.formState.errors,
      experienceState.includeExperience,
      experienceState.isFormValid,
      experienceState.selectedProduct,
      passengerForm.formState.errors,
    ],
  )

  /**
   * Comprehensive step validation according to requirements
   */
  const isStepValid = useCallback(
    (step: MasterStep): boolean => {
      // For form-based steps, check React Hook Form errors
      if (isFormBasedStep(step)) {
        return !getFormErrors(step)
      }

      // For non-form steps, use custom validation
      const errors = getStepValidationErrors(step)
      setValidationErrors((prev) => ({ ...prev, [step]: errors }))
      return errors.length === 0
    },
    [getFormErrors, getStepValidationErrors],
  )

  /**
   * Check if a step uses React Hook Form for error handling
   */
  const isFormBasedStep = (step: MasterStep): boolean => {
    return [MasterStep.PassengerDetails, MasterStep.OrderCompletion].includes(
      step,
    )
  }

  // Agent Selection Handler
  const handleChangeAgent = (agent: AgentData | null) => {
    setSelectedAgent(agent)

    if (agent && selectedOrderBy === 'agent') {
      if (selectedDepartureProduct) {
        setSelectedDepartureProduct(null)
        boatPriceForm.setValue('departurePrices', [])
      }

      if (selectedReturnProduct) {
        setSelectedReturnProduct(null)
        boatPriceForm.setValue('returnPrices', [])
      }

      if (transportDetailPayload) {
        setTransportDetailPayload({
          departure_pickup: null,
          departure_dropoff: null,
          return_pickup: null,
          return_dropoff: null,
        })
      }

      if (experienceState.includeExperience) {
        setExperienceState((prev) => ({
          ...prev,
          selectedProduct: null,
          adjustablePrices: [],
          bookingData: null,
          isFormValid: false,
        }))
      }

      setCurrentMasterStep(MasterStep.ChooseBoats)
      setCurrentChooseBoatStep(ChooseBoatStep.ChooseDeparture)
      scrollToRef(mainContentRef)
    }
  }

  // Search Boats Handlers
  const handleSearchBoats = searchForm.handleSubmit(async (data) => {
    try {
      setLoadingBoats(true)

      const fastboatProducts = await searchFastboatProducts({
        merchant_id: merchant?.id as number,
        departure: data.selectedDeparture.harbor,
        arrival: data.selectedArrival.harbor,
        depart_date: data.departureDate,
        return_date: data.trip === Trip.RETURN ? data.returnDate : undefined,
        trip: data.trip,
      })

      setAggregatedFastboatProducts((prev) => ({
        ...prev,
        departures: fastboatProducts.departures ?? [],
        returns: fastboatProducts.returns ?? [],
      }))

      setBoatFound(true)

      setMatchedRoute(
        props.fastboatRoutes.data.find((route) => {
          return (
            route.departure_harbor === data.selectedDeparture.harbor &&
            route.arrival_harbor === data.selectedArrival.harbor
          )
        }) ?? null,
      )
    } catch (e) {
      if (e instanceof AxiosError) {
        if (e.status === HttpStatusCode.NOT_FOUND) {
          showPopup({
            title: 'No Boats Found for Selected Route',
            message:
              'No boats were found for the selected route. Please change to another route.',
            type: 'info',
          })
          setBoatFound(false)
          return
        }
      }

      setBoatFound(false)
      toast.error('An unexpected error occurred while searching boats.')
    } finally {
      setLoadingBoats(false)
    }
  })

  // Select Departure Handler
  function handleSelectDeparture(product: FastboatProduct) {
    const departureProduct: FastboatProduct = {
      ...product,
      prices: product.prices.map((price) => {
        if (selectedOrderBy !== 'agent' || !selectedAgent) {
          return {
            ...price,
            agent_rate: 0,
            agent_commission: 0,
          }
        }

        return {
          ...price,
          agent_rate: price.agent_rate,
          agent_commission: price.price - price.agent_rate,
        }
      }),
    }

    setSelectedDepartureProduct(departureProduct)

    boatPriceForm.setValue('departurePrices', departureProduct.prices)

    // Reset transport details
    setTransportDetailPayload({
      ...transportDetailPayload,
      departure_dropoff: null,
      departure_pickup: null,
    })

    // Go to return boat selection if trip is RETURN
    if (searchForm.getValues('trip') === 'RETURN' && !selectedReturnProduct) {
      setCurrentChooseBoatStep(ChooseBoatStep.ChooseReturn)
      scrollToRef(returnProductRef)
      return
    }

    // If product support transport, go to transport selection
    // Except for merchant order type, because it is only use for boat transfer
    if (departureProduct.include_transport && selectedOrderBy !== 'merchant') {
      setCurrentChooseBoatStep(ChooseBoatStep.TransportServiceOffering)
      scrollToRef(transportRef)
      return
    }

    // Create initial passengers when the departure product changes
    const departurePassengers = createInitialPassengers({
      passengerCount: {
        adult: searchForm.getValues('passengerCount.adult'),
        child: searchForm.getValues('passengerCount.child'),
        infant: searchForm.getValues('passengerCount.infant'),
      },
      passengerRate: {
        adult: adultDepartureRate || DEFAULT_PASSENGER_RATE.adult,
        child: childDepartureRate || DEFAULT_PASSENGER_RATE.child,
        infant: infantDepartureRate || DEFAULT_PASSENGER_RATE.infant,
      },
    })

    passengerForm.setValue('departurePassengers', departurePassengers)
    // Trigger validation after setting values
    passengerForm.trigger('departurePassengers')

    // If product doesnt support transport and trip is ONE_WAY, go to passenger form
    setDisabledNext(false)
    handleChangeMasterStep(MasterStep.PassengerDetails)
    scrollToRef(passengerDetailRef)
  }

  // Select Fast Boat Return Handler
  function handleSelectReturn(product: FastboatProduct) {
    const returnProduct: FastboatProduct = {
      ...product,
      prices: product.prices.map((price) => {
        if (selectedOrderBy !== 'agent' || !selectedAgent) {
          return {
            ...price,
            agent_rate: 0,
            agent_commission: 0,
          }
        }

        return {
          ...price,
          agent_rate: price.agent_rate,
          agent_commission: price.price - price.agent_rate,
        }
      }),
    }

    setSelectedReturnProduct(returnProduct)

    boatPriceForm.setValue('returnPrices', returnProduct.prices)

    // Reset transport detail
    setTransportDetailPayload({
      ...transportDetailPayload,
      return_dropoff: null,
      return_pickup: null,
    })

    if (
      (selectedDepartureProduct?.include_transport &&
        selectedOrderBy !== 'merchant') ||
      (returnProduct.include_transport && selectedOrderBy !== 'merchant')
    ) {
      setCurrentChooseBoatStep(ChooseBoatStep.TransportServiceOffering)
      scrollToRef(transportRef)
      return
    }

    // Create initial passengers when the return product changes
    const returnPassengers = createInitialPassengers({
      passengerCount: {
        adult: searchForm.getValues('passengerCount.adult'),
        child: searchForm.getValues('passengerCount.child'),
        infant: searchForm.getValues('passengerCount.infant'),
      },
      passengerRate: {
        adult: adultReturnRate || DEFAULT_PASSENGER_RATE.adult,
        child: childReturnRate || DEFAULT_PASSENGER_RATE.child,
        infant: infantReturnRate || DEFAULT_PASSENGER_RATE.infant,
      },
    })

    passengerForm.setValue('returnPassengers', returnPassengers)
    // Trigger validation after setting values
    passengerForm.trigger('returnPassengers')

    setDisabledNext(false)
    handleChangeMasterStep(MasterStep.PassengerDetails)
    scrollToRef(passengerDetailRef)
  }

  // Change Master Step Handler
  function handleChangeMasterStep(step: MasterStep) {
    setCurrentMasterStep(step)

    // Update disabled state based on current step validation
    setDisabledNext(!isStepValid(step))
  }

  // Stepper Handlers
  const goToPrevious = () => {
    if (currentMasterStep === MasterStep.OrderCompletion) {
      updateCart({
        ...cart,
        total_marketplace_cost: 0,
      })
    }

    const updatedMasterStep = currentMasterStep - 1

    if (currentMasterStep > 0) {
      handleChangeMasterStep(updatedMasterStep)
    }

    if (
      updatedMasterStep === MasterStep.PassengerDetails &&
      (selectedOrderBy === 'merchant' || selectedOrderBy === 'marketplace')
    ) {
      // Clear cart to prevent duplicate entries in single flow transaction
      clearCart()
    }

    scrollToRef(mainContentRef)
  }

  const goToNext = () => {
    // Validate current step before proceeding
    if (!isStepValid(currentMasterStep)) {
      // For form-based steps, errors are displayed inline by React Hook Form
      // For non-form steps, show validation errors via toast
      if (!isFormBasedStep(currentMasterStep)) {
        const errors = validationErrors[currentMasterStep] || []
        if (errors.length > 0) {
          toast.error(errors.join('. '))
        }
      } else {
        // For form-based steps, show a generic message since errors are inline
        toast.error('Please correct the errors in the form before proceeding.')
      }
      return
    }

    if (currentMasterStep < TOTAL_MASTER_STEPS - 1) {
      const updatedMasterStep = currentMasterStep + 1

      if (
        updatedMasterStep === MasterStep.OrderCompletion &&
        (selectedOrderBy === 'merchant' || selectedOrderBy === 'marketplace')
      ) {
        setProcessing(true)

        const boatOrderPayload = boatOrderHelpers.constructPayload({
          trip: searchForm.getValues('trip'),
          selectedDepartureProduct,
          selectedReturnProduct,
          passengerData: passengerForm.getValues(),
          samePassenger,
          departurePrices: boatPriceForm.getValues('departurePrices'),
          returnPrices: boatPriceForm.getValues('returnPrices'),
          selectedOrderBy,
          departureDate: searchForm.getValues('departureDate'),
          returnDate: searchForm.getValues('returnDate'),
        })

        const transportOrders = transportOrderHelpers.constructOrderPayload(
          selectedOrderBy,
          transportDetailPayload,
        )

        const fastboatOrder: FastboatOrderPayload = {
          ...boatOrderPayload,
          transport_orders: transportOrders.map((transportOrder) => ({
            ...transportOrder,
            transport_order_items: transportOrder.transport_order_items?.map(
              (transportOrderItem) => {
                if (transportOrderItem.trip_segment === TripSegment.DEPARTURE) {
                  return {
                    ...transportOrderItem,
                    booking_date: searchForm.getValues('departureDate'),
                  }
                }

                if (
                  transportOrderItem.trip_segment === TripSegment.RETURN &&
                  searchForm.getValues('trip') === 'RETURN' &&
                  searchForm.getValues('returnDate')
                ) {
                  return {
                    ...transportOrderItem,
                    booking_date: searchForm.getValues('returnDate') as string,
                  }
                }

                return transportOrderItem
              },
            ),
          })),
        }

        addFastboatToCart({
          fastboatOrder,
          orderBy: selectedOrderBy as OrderByType,
          agentId: selectedAgent?.id,
          marketplaceId: selectedMarketplace?.id,
        })

        setProcessing(false)
      }

      handleChangeMasterStep(updatedMasterStep)
      scrollToRef(mainContentRef)
    }
  }

  const handleAddToCart = () => {
    setSubmitting(true)

    const boatOrderPayload = boatOrderHelpers.constructPayload({
      trip: searchForm.getValues('trip'),
      selectedDepartureProduct,
      selectedReturnProduct,
      passengerData: passengerForm.getValues(),
      samePassenger,
      departurePrices: boatPriceForm.getValues('departurePrices'),
      returnPrices: boatPriceForm.getValues('returnPrices'),
      selectedOrderBy,
      departureDate: searchForm.getValues('departureDate'),
      returnDate: searchForm.getValues('returnDate'),
    })

    const activityOrderPayload = activityOrderHelpers.constructPayload({
      experienceState,
      selectedOrderBy,
    })

    const transportOrders = transportOrderHelpers.constructOrderPayload(
      selectedOrderBy as OrderByType,
      transportDetailPayload,
    )

    const fastboatOrder: FastboatOrderPayload = {
      ...boatOrderPayload,
      transport_orders: transportOrders.map((transportOrder) => ({
        ...transportOrder,
        transport_order_items: transportOrder.transport_order_items?.map(
          (transportOrderItem) => {
            if (transportOrderItem.trip_segment === TripSegment.DEPARTURE) {
              return {
                ...transportOrderItem,
                booking_date: searchForm.getValues('departureDate'),
              }
            }

            if (
              transportOrderItem.trip_segment === TripSegment.RETURN &&
              searchForm.getValues('trip') === 'RETURN' &&
              searchForm.getValues('returnDate')
            ) {
              return {
                ...transportOrderItem,
                booking_date: searchForm.getValues('returnDate') as string,
              }
            }

            return transportOrderItem
          },
        ),
      })),
    }

    props.onAddToCart({
      fastboatOrder,
      activityOrder:
        experienceState.includeExperience && activityOrderPayload
          ? activityOrderPayload
          : null,
      orderBy: selectedOrderBy as OrderByType,
      agentId: selectedAgent?.id,
      marketplaceId: selectedMarketplace?.id,
    })

    setSubmitting(false)
  }

  const processBooking = async () => {
    try {
      setSubmitting(true)

      const billingData = billingFormRef.current?.getValues()

      // Prepare cart for checkout by removing the serviceType field
      const orderPayload = prepareCartForCheckout()

      const checkoutPayload: CreateOrderPayload = {
        ...orderPayload,
        billing_name: billingData?.billingName,
        billing_email: billingData?.billingEmail,
        billing_phone: billingData?.billingPhone,
        payment_method_code: billingData?.paymentMethod,
        booking_source: null,
        acc_ref_id:
          billingData?.paymentMethod === 'ACCOUNT'
            ? billingData?.orderId
            : null,
        refundable:
          cart.order_by === 'marketplace' || cart.order_by === 'merchant'
            ? false
            : refundable,
        reschedulable: cart.order_by === 'marketplace' ? false : reschedulable,
        order_items: {
          ...orderPayload.order_items,
          fastboats: orderPayload.order_items?.fastboats?.map(
            (fastboat, index) => {
              // The acc ref only and must be set to the first fastboat order item
              if (index === 0) {
                return {
                  ...fastboat,
                  acc_ref_id:
                    billingData?.paymentMethod === 'ACCOUNT'
                      ? billingData?.fastboatOrderId
                      : null,
                  transferred_trip_segment:
                    billingData?.transferredTripSegment || null,
                }
              }

              return fastboat
            },
          ),
        },
      }

      const data = await createOrder({
        merchantId: merchant?.id as number,
        payload: checkoutPayload,
      })

      showPopup({
        type: 'success',
        title: 'Booking Created',
        message:
          'Booking has been created successfully. You will be redirected to the booking details page.',
      })

      // Clear the cart after successful checkout
      clearCart()

      router.replace(`/merchant-dashboard/${merchant?.id}/bookings/${data.id}`)
    } catch (e) {
      handleApiError(
        e,
        'An unexpected error occurred while creating booking. Please try again',
        (formErrors) => {
          Object.values(formErrors).forEach((messages) => {
            messages.forEach((message) => toast.error(message))
          })
        },
      )
    } finally {
      setSubmitting(false)
    }
  }

  // Trigger validation on mount and when passenger count changes
  useEffect(() => {
    passengerForm.trigger()
  }, [passengerForm])

  // Update departure passenger form when departure product changes
  useEffect(() => {
    if (selectedDepartureProduct) {
      const departurePassengers = createInitialPassengers({
        passengerCount: {
          adult: searchForm.getValues('passengerCount.adult'),
          child: searchForm.getValues('passengerCount.child'),
          infant: searchForm.getValues('passengerCount.infant'),
        },
        passengerRate: {
          adult: adultDepartureRate || DEFAULT_PASSENGER_RATE.adult,
          child: childDepartureRate || DEFAULT_PASSENGER_RATE.child,
          infant: infantDepartureRate || DEFAULT_PASSENGER_RATE.infant,
        },
      })

      passengerForm.setValue('departurePassengers', departurePassengers)
      // Trigger validation after setting values
      passengerForm.trigger('departurePassengers')
    }
  }, [
    selectedDepartureProduct,
    adultDepartureRate,
    childDepartureRate,
    infantDepartureRate,
    passengerForm,
    searchForm,
  ])

  // Update return passengers when return product changes
  useEffect(() => {
    if (searchForm.getValues('trip') === 'RETURN' && selectedReturnProduct) {
      const returnPassengers = createInitialPassengers({
        passengerCount: {
          adult: searchForm.getValues('passengerCount.adult'),
          child: searchForm.getValues('passengerCount.child'),
          infant: searchForm.getValues('passengerCount.infant'),
        },
        passengerRate: {
          adult: adultReturnRate || DEFAULT_PASSENGER_RATE.adult,
          child: childReturnRate || DEFAULT_PASSENGER_RATE.child,
          infant: infantReturnRate || DEFAULT_PASSENGER_RATE.infant,
        },
      })

      passengerForm.setValue('returnPassengers', returnPassengers)
      // Trigger validation after setting values
      passengerForm.trigger('returnPassengers')
    } else if (searchForm.getValues('trip') === 'ONE_WAY') {
      passengerForm.setValue('returnPassengers', [])
      passengerForm.trigger('returnPassengers')
    }
  }, [
    selectedReturnProduct,
    adultReturnRate,
    childReturnRate,
    infantReturnRate,
    passengerForm,
    searchForm,
  ])

  // Handle same passenger
  useEffect(() => {
    if (searchForm.getValues('trip') === 'RETURN') {
      if (samePassenger) {
        passengerForm.setValue('returnPassengers', [])
      } else if (selectedReturnProduct) {
        passengerForm.setValue(
          'returnPassengers',
          createInitialPassengers({
            passengerCount: {
              adult: searchForm.getValues('passengerCount.adult'),
              child: searchForm.getValues('passengerCount.child'),
              infant: searchForm.getValues('passengerCount.infant'),
            },
            passengerRate: {
              adult: adultReturnRate || DEFAULT_PASSENGER_RATE.adult,
              child: childReturnRate || DEFAULT_PASSENGER_RATE.child,
              infant: infantReturnRate || DEFAULT_PASSENGER_RATE.infant,
            },
          }),
        )

        passengerForm.trigger()
      }
    }
  }, [
    samePassenger,
    adultReturnRate,
    childReturnRate,
    infantReturnRate,
    selectedReturnProduct,
    passengerForm,
    searchForm,
  ])

  // Comprehensive validation system - validate current step when dependencies change
  useEffect(() => {
    setDisabledNext(!isStepValid(currentMasterStep))
  }, [
    isStepValid,
    selectedOrderBy,
    selectedAgent,
    currentMasterStep,
    selectedDepartureProduct,
    selectedReturnProduct,
    includeTransport,
    transportDetailPayload,
    searchForm,
    passengerForm.formState.errors,
    passengerForm.formState.isValid,
    boatPriceForm.formState.errors,
    boatPriceForm.formState.isValid,
    experienceState.includeExperience,
    experienceState.selectedProduct,
    experienceState.isFormValid,
  ])

  // Set predefined payment method when order by changes either to Merchant or Marketplace
  useEffect(() => {
    setBillingPaymentState((prev) => ({
      ...prev,
      paymentMethod:
        selectedOrderBy === 'merchant'
          ? 'ACCOUNT'
          : selectedOrderBy === 'marketplace'
            ? 'OTA'
            : prev.paymentMethod,
    }))
  }, [selectedOrderBy])

  // Handler functions for OrderBySelector
  const handleChangeMarketplace = (marketplace: Marketplace | null) => {
    setSelectedMarketplace(marketplace)

    if (marketplace && selectedOrderBy === 'marketplace') {
      setCurrentMasterStep(MasterStep.ChooseBoats)
      scrollToRef(mainContentRef)
    }
  }

  if (!merchant) {
    return <FullPageLoader />
  }

  return (
    <Stepper totalSteps={TOTAL_MASTER_STEPS} step={currentMasterStep}>
      <Stepper.Indicators
        className="mx-auto"
        labels={stepLabels}
        icons={stepIcons}
      />

      <Stepper.Content ref={mainContentRef}>
        {/* Order Placed By */}
        <div className="my-12 space-y-6 gap-4 lg:gap-8">
          <OrderBySelector
            serviceType="boat_ticket"
            selectedOrderBy={selectedOrderBy}
            selectedAgent={selectedAgent}
            selectedMarketplace={selectedMarketplace}
            agents={props.agents}
            marketplaces={props.marketplaces}
            onAgentChange={handleChangeAgent}
            onMarketplaceChange={handleChangeMarketplace}
            onOrderByChange={setSelectedOrderBy}
          />
        </div>

        {/* Search Boat Step */}
        <div className="my-12">
          <BoatSearchForm
            form={searchForm}
            searching={loadingBoats}
            passengerAgeGroup={merchant?.passenger_age_group}
            fastboatRoutes={props.fastboatRoutes.data}
            handleSearch={handleSearchBoats}
          />

          <ChooseBoat
            boatFound={boatFound}
            chooseBoatSteps={chooseBoatSteps}
            currentChooseBoatStep={currentChooseBoatStep}
            loadingBoats={loadingBoats}
            searchParams={{
              trip: searchForm.getValues('trip'),
              depart_date: searchForm.getValues('departureDate'),
              return_date: searchForm.getValues('returnDate'),
              departure: searchForm.getValues('selectedDeparture.harbor'),
              arrival: searchForm.getValues('selectedArrival.harbor'),
              adult: searchForm.getValues('passengerCount.adult'),
              child: searchForm.getValues('passengerCount.child'),
              infant: searchForm.getValues('passengerCount.infant'),
            }}
            selectedDepartureProduct={selectedDepartureProduct}
            selectedReturnProduct={selectedReturnProduct}
            setCurrentChooseBoatStep={setCurrentChooseBoatStep}
          />
        </div>

        {/* Passenger Detail Step */}
        <div className="my-12" ref={passengerDetailRef}>
          <div className="grid grid-cols-12 gap-4 lg:gap-8">
            {/* Passenger Detail Form */}
            <div className="col-span-12 xl:col-span-8">
              <PassengerDetail
                countries={props.countries.data}
                trip={searchForm.getValues('trip')}
                passengerForm={passengerForm}
                samePassenger={samePassenger}
                setSamePassenger={setSamePassenger}
                passengerCount={{
                  adult: searchForm.getValues('passengerCount.adult'),
                  child: searchForm.getValues('passengerCount.child'),
                  infant: searchForm.getValues('passengerCount.infant'),
                }}
              />
            </div>

            {/* Price Management Form */}
            <div className="col-span-12 lg:col-span-4">
              <PriceManagementForm
                form={boatPriceForm}
                departurePrices={selectedDepartureProduct?.prices || []}
                returnPrices={selectedReturnProduct?.prices || []}
                tripType={searchForm.getValues('trip')}
                orderBy={selectedOrderBy}
                passengerCount={{
                  adult: searchForm.getValues('passengerCount.adult'),
                  child: searchForm.getValues('passengerCount.child'),
                  infant: searchForm.getValues('passengerCount.infant'),
                }}
              />
            </div>
          </div>
        </div>

        {/* Experience Step */}
        {selectedOrderBy === 'merchant' || selectedOrderBy === 'marketplace' ? (
          <div className="my-12 grid grid-cols-12 gap-6 lg:gap-12 space-y-8">
            <div className="col-span-12 lg:col-span-6 space-y-4">
              <OrderSummary />
            </div>

            <div className="col-span-12 lg:col-span-6 space-y-8">
              <BillingPaymentForm
                ref={billingFormRef}
                orderBy={selectedOrderBy}
                initialValues={billingPaymentState}
                onValidationChange={setIsBillingPaymentValid}
                onFormDataChange={(billingData) => {
                  setBillingPaymentState((prev) => ({
                    ...prev,
                    ...billingData,
                  }))
                }}
              />

              {/* Booking Policies */}
              {cart.order_by !== 'marketplace' &&
                cart.order_by !== 'merchant' && (
                  <div className="w-full min-w-0">
                    <BookingPolicies
                      refundable={refundable}
                      reschedulable={reschedulable}
                      onRefundableChange={setRefundable}
                      onReschedulableChange={setReschedulable}
                    />
                  </div>
                )}
            </div>
          </div>
        ) : (
          <div className="my-12">
            <Experience
              orderBy={selectedOrderBy}
              experienceState={experienceState}
              selectedAgent={selectedAgent}
              activityProducts={props.activityProducts}
              onStateChange={(state) => {
                setExperienceState(() => ({ ...state }))
              }}
            />
          </div>
        )}
      </Stepper.Content>

      {currentMasterStep === MasterStep.OrderCompletion ? (
        <Stepper.Navigation
          showStepCount
          disabled={disabledNext || submitting || processing}
          prevButtonHandler={goToPrevious}
          nextButtonHandler={
            selectedOrderBy === 'merchant' || selectedOrderBy === 'marketplace'
              ? processBooking
              : handleAddToCart
          }
          nextButtonType="submit"
          nextIcon={
            selectedOrderBy === 'merchant' ||
            selectedOrderBy === 'marketplace' ? null : (
              <LuShoppingCart className="h-5 w-5 ml-2" />
            )
          }
          nextLabel={
            selectedOrderBy === 'merchant' || selectedOrderBy === 'marketplace'
              ? 'Process Booking'
              : 'Add to Cart'
          }
        />
      ) : currentMasterStep === MasterStep.OrderPlacedBy ? (
        <Stepper.Navigation
          showStepCount
          enablePrev
          disabled={disabledNext || submitting}
          nextButtonHandler={goToNext}
          prevButtonHandler={() => {
            props.setSelectedServiceType(null)
          }}
          prevLabel="Service Selection"
        />
      ) : (
        <Stepper.Navigation
          showStepCount
          disabled={disabledNext}
          nextButtonHandler={goToNext}
          prevButtonHandler={goToPrevious}
        />
      )}

      <PopupModal
        type={popup.type}
        title={popup.title}
        show={popup.show}
        message={popup.message}
        onClose={hidePopup}
      />
    </Stepper>
  )
}
