import React, { useCallback, useEffect, useRef, useState } from 'react'
import {
  LuReceiptText,
  LuShapes,
  LuShieldCheck,
  LuShoppingCart,
  LuUser,
} from 'react-icons/lu'
import { toast } from 'react-toastify'

import { AgentData } from '@/app/(dashboard)/agents/types'
import { HarborTransferProduct } from '@/lib/types/product/harbor-transfer'
import { TourPackageProduct } from '@/lib/types/product/tour-package'
import Stepper from '@/lib/components/stepper/Index'
import { scrollToRef } from '@/lib/utils/dom'
import { ServiceType } from './ServiceTypeSelector'
import {
  AdjustablePriceData,
  TourPackageState,
} from './tour-package-orders/types'
import OrderBySelector from './OrderBySelector'
import BookingDetail, {
  BookingDetailRef,
} from './tour-package-orders/BookingDetail'
import BillingPaymentForm, {
  BillingPaymentFormRef,
} from './billings/BillingPaymentForm'
import TourPackageProductList from './tour-package-orders/TourPackageProductList'
import * as tourPackageOrderHelpers from './tour-package-orders/helpers'
import * as transportOrderHelpers from './transports/helpers'
import PopupModal from '@/lib/components/modals/PopupModal'
import { usePopup } from '@/lib/hooks/usePopup'
import { format } from 'date-fns'
import { CreateOrderPayload, TourPackageOrderPayload } from '../types'
import { Marketplace } from '@/app/(dashboard)/marketplaces/types'
import OrderSummary from './billings/OrderSummary'
import { BillingPaymentFormData } from './billings/schemas'
import BookingPolicies from './BookingPolicies'
import { useCart } from '@/lib/context/CartContext'
import { createOrder } from '@/lib/services/order-services'
import { useMerchant } from '@/lib/context/MerchantContext'
import { useRouter } from 'next/navigation'
import { handleApiError } from '@/lib/utils/error-handler'

interface PackageBookingProps {
  onAddToCart: ({
    tourPackageOrder,
    orderBy,
    agentId,
  }: {
    tourPackageOrder: TourPackageOrderPayload
    orderBy: OrderByType
    agentId?: number
  }) => void
  tourPackageProducts: {
    isLoading: boolean
    data: TourPackageProduct[]
  }
  harborTransferProducts: {
    isLoading: boolean
    data: HarborTransferProduct[]
  }
  agents: {
    isLoading: boolean
    data: AgentData[]
  }
  marketplaces: {
    isLoading: boolean
    data: Marketplace[]
  }
  setSelectedServiceType: (type: ServiceType | null) => void
}

const INITIAL_STEP = 0
const DEFAULT_TOTAL_PAX = 1
const TOTAL_STEPS = 3
const MARKETPLACE_TOTAL_STEPS = 4

enum Step {
  OrderPlacedBy = 0,
  ChoosePackage = 1,
  BookingDetails = 2,
  BillingDetails = 3,
}

const DEFAULT_RATES: Record<'adult' | 'child', AdjustablePriceData> = {
  adult: {
    id: 0,
    price_type: 'tiered',
    net_rate: 0,
    category: 'adult',
    price: 0,
    agent_rate: 0,
    agent_commission: 0,
    pax_type: 'range',
    min_pax: DEFAULT_TOTAL_PAX,
    max_pax: DEFAULT_TOTAL_PAX,
  },
  child: {
    id: 0,
    price_type: 'tiered',
    net_rate: 0,
    category: 'child',
    price: 0,
    agent_rate: 0,
    agent_commission: 0,
    pax_type: 'range',
    min_pax: DEFAULT_TOTAL_PAX,
    max_pax: DEFAULT_TOTAL_PAX,
  },
}

export default function PackageBooking(props: PackageBookingProps) {
  const router = useRouter()
  const [processing, setProcessing] = useState(false)
  const [submitting, setSubmitting] = useState(false)
  const { popup, hidePopup, showPopup } = usePopup()
  const { merchant } = useMerchant()
  const {
    prepareCartForCheckout,
    clearCart,
    addTourPackageToCart,
    updateCart,
    cart,
  } = useCart()

  // Refs
  const mainContentRef = useRef<HTMLDivElement>(null)
  const choosePackageRef = useRef<HTMLDivElement>(null)
  const bookingDetailRef = useRef<BookingDetailRef>(null)
  const billingFormRef = useRef<BillingPaymentFormRef>(null)

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

  // Tour Package States
  const [tourPackageState, setTourPackageState] = useState<TourPackageState>({
    selectedTotalPax: DEFAULT_TOTAL_PAX,
    selectedProduct: null,
    adjustablePrices: [DEFAULT_RATES.adult, DEFAULT_RATES.child],
    bookingData: null,
    isBookingValid: false,
    transport: {
      pickup_details: null,
      dropoff_details: null,
    },
  })

  // 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)

  // Stepper States
  const [disabledNext, setDisabledNext] = useState(false)
  const [currentStep, setCurrentStep] = useState(INITIAL_STEP)
  const [selectedAgent, setSelectedAgent] = useState<AgentData | null>(null)
  const [selectedMarketplace, setSelectedMarketplace] =
    useState<Marketplace | null>(null)
  const stepLabels = [
    'Order Placed By',
    'Choose Package',
    'Booking Details',
    'Billing Details',
  ]
  const stepIcons = [
    <LuUser key="order-placed-by" className="h-5 w-5" />,
    <LuShapes key="choose-package" className="h-5 w-5" />,
    <LuReceiptText key="booking-details" className="h-5 w-5" />,
    <LuShieldCheck key="billing-details" className="h-5 w-5" />,
  ]
  const [selectedOrderBy, setSelectedOrderBy] = useState<OrderByType | null>(
    null,
  )

  const handleScrollToRef = (step: Step) => {
    switch (step) {
      case Step.ChoosePackage:
        scrollToRef(choosePackageRef)
        break
      case Step.BookingDetails:
        if (bookingDetailRef.current?.scrollToElement) {
          scrollToRef({ current: bookingDetailRef.current.scrollToElement })
        } else {
          scrollToRef(mainContentRef)
        }
        break
      default:
        scrollToRef(mainContentRef)
        break
    }
  }

  function handleChangeOrderBy(orderBy: OrderByType | null) {
    setSelectedOrderBy(orderBy)

    // Only move to next step if the selection is complete
    // For direct_guest: can move immediately
    // For agent and marketplace: only move if an agent is already selected
    if (
      orderBy === 'direct_guest' ||
      (orderBy === 'agent' && selectedAgent) ||
      (orderBy === 'marketplace' && selectedMarketplace)
    ) {
      setCurrentStep(Step.ChoosePackage)
      handleScrollToRef(Step.ChoosePackage)
    }
  }

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

    if (agent && selectedOrderBy === 'agent') {
      setTourPackageState({
        selectedTotalPax: DEFAULT_TOTAL_PAX,
        selectedProduct: null,
        adjustablePrices: [DEFAULT_RATES.adult, DEFAULT_RATES.child],
        bookingData: null,
        isBookingValid: false,
        transport: {
          pickup_details: null,
          dropoff_details: null,
        },
      })

      setCurrentStep(Step.ChoosePackage)
      scrollToRef(mainContentRef)
    }
  }

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

    if (marketplace && selectedOrderBy === 'marketplace') {
      setCurrentStep(Step.ChoosePackage)
      scrollToRef(mainContentRef)
    }
  }

  // Stepper Handlers
  const goToPrevious = () => {
    if (currentStep === Step.BillingDetails) {
      updateCart({
        ...cart,
        total_marketplace_cost: 0,
      })
    }

    const updatedStep = currentStep - 1

    setCurrentStep(updatedStep)
    handleScrollToRef(updatedStep)

    if (
      updatedStep === Step.BookingDetails &&
      selectedOrderBy === 'marketplace'
    ) {
      // Clear cart to prevent duplicate entries in single flow transaction
      clearCart()
    }
  }
  const goToNext = () => {
    // Validate current step before proceeding
    if (!isStepValid(currentStep)) {
      // For non-form steps, show validation errors via toast
      if (!isFormBasedStep(currentStep)) {
        const errors = validationErrors[currentStep] || []
        errors?.forEach((error) => toast.error(error))
      } 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 (
      currentStep < TOTAL_STEPS - 1 ||
      currentStep < MARKETPLACE_TOTAL_STEPS - 1
    ) {
      const updatedStep = currentStep + 1

      if (
        updatedStep === Step.BillingDetails &&
        selectedOrderBy === 'marketplace'
      ) {
        setProcessing(true)

        const adultRate = tourPackageState.adjustablePrices?.find(
          (price) => price.category === 'adult',
        )
        const childRate = tourPackageState.adjustablePrices?.find(
          (price) => price.category === 'child',
        )

        if (!adultRate || !childRate) {
          toast.error('Please ensure both adult and child rates are set.')
          setProcessing(false)
          return
        }

        const tourPackageOrderPayload =
          tourPackageOrderHelpers.constructPayload({
            tourPackageState,
            adultRate,
            childRate,
            selectedOrderBy,
          })

        const transportOrders = transportOrderHelpers.constructOrderPayload(
          selectedOrderBy,
          tourPackageState.transport,
        )

        const tourPackageOrder: TourPackageOrderPayload = {
          ...tourPackageOrderPayload,
          transport_orders: transportOrders?.map((transportOrder) => ({
            ...transportOrder,
            transport_order_items: transportOrder.transport_order_items?.map(
              (transportOrderItem) => ({
                ...transportOrderItem,
                booking_date: format(
                  tourPackageState.bookingData?.booking_date as Date,
                  'yyyy-MM-dd',
                ),
              }),
            ),
          })),
        }

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

        setProcessing(false)
      }

      setCurrentStep(updatedStep)
      handleScrollToRef(updatedStep)
    }
  }

  /**
   * Get React Hook Form errors for form-based steps
   */
  const getFormErrors = useCallback(
    (step: Step): boolean => {
      switch (step) {
        case Step.BookingDetails:
          return !tourPackageState.isBookingValid
        case Step.BillingDetails:
          if (selectedOrderBy === 'marketplace') {
            return !isBillingPaymentValid
          }

          return false
        default:
          return false
      }
    },
    [tourPackageState.isBookingValid, isBillingPaymentValid, selectedOrderBy],
  )

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

      switch (step) {
        case Step.OrderPlacedBy:
          if (!selectedOrderBy) {
            errors.push('Please select how the order is placed.')
          }
          if (selectedOrderBy === 'agent' && !selectedAgent) {
            errors.push('Please select an agent.')
          }
          break
        case Step.ChoosePackage:
          if (!tourPackageState.selectedProduct) {
            errors.push('Please select a tour package product.')
          }
          break
      }

      return errors
    },
    [selectedAgent, selectedOrderBy, tourPackageState.selectedProduct],
  )

  /**
   * Check if a step uses React Hook Form for error handling
   */
  const isFormBasedStep = useCallback(
    (step: Step): boolean => {
      if (selectedOrderBy === 'marketplace') {
        return [Step.BookingDetails, Step.BillingDetails].includes(step)
      }

      return step === Step.BookingDetails
    },
    [selectedOrderBy],
  )

  /**
   * Comprehensive step validation according to requirements
   */
  const isStepValid = useCallback(
    (step: Step): 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, isFormBasedStep],
  )

  // Tour Package Handlers
  const handleChoosePackage = (product: TourPackageProduct) => {
    const mappedPrices = product.prices.map((price) => {
      return {
        ...price,
        agent_rate: selectedOrderBy === 'agent' ? price.agent_rate : 0,
        agent_commission:
          selectedOrderBy === 'agent' ? price.price - price.agent_rate : 0,
      }
    })

    const adjustablePrices = mappedPrices
      .filter((price) => {
        if (price.price_type === 'flat') return true

        return (
          (price.category === 'adult' &&
            price.min_pax <= DEFAULT_TOTAL_PAX &&
            (price.max_pax === 0 || price.max_pax >= DEFAULT_TOTAL_PAX)) ||
          price.category === 'child'
        )
      })
      .sort((priceA, priceB) => priceA.category.localeCompare(priceB.category))

    setTourPackageState((prev) => ({
      ...prev,
      selectedProduct: product,
      selectedTotalPax: DEFAULT_TOTAL_PAX,
      adjustablePrices,
      bookingData: null,
      isBookingValid: false,
      transport: {
        pickup_details: null,
        dropoff_details: null,
      },
    }))

    setCurrentStep(Step.BookingDetails)
    handleScrollToRef(Step.BookingDetails)
  }

  async function handleAddToCart() {
    setSubmitting(true)

    const adultRate = tourPackageState.adjustablePrices?.find(
      (price) => price.category === 'adult',
    )
    const childRate = tourPackageState.adjustablePrices?.find(
      (price) => price.category === 'child',
    )

    if (!adultRate || !childRate) {
      toast.error('Please ensure both adult and child rates are set.')
      setSubmitting(false)
      return
    }

    const tourPackageOrderPayload = tourPackageOrderHelpers.constructPayload({
      tourPackageState,
      adultRate,
      childRate,
      selectedOrderBy,
    })

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

    const tourPackageOrder: TourPackageOrderPayload = {
      ...tourPackageOrderPayload,
      transport_orders: transportOrders?.map((transportOrder) => ({
        ...transportOrder,
        transport_order_items: transportOrder.transport_order_items?.map(
          (transportOrderItem) => ({
            ...transportOrderItem,
            booking_date: format(
              tourPackageState.bookingData?.booking_date as Date,
              'yyyy-MM-dd',
            ),
          }),
        ),
      })),
    }

    props.onAddToCart({
      tourPackageOrder,
      orderBy: selectedOrderBy as OrderByType,
      agentId: selectedAgent?.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: null,
        refundable: cart.order_by === 'marketplace' ? false : refundable,
        reschedulable: cart.order_by === 'marketplace' ? false : reschedulable,
      }

      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)
    }
  }

  useEffect(() => {
    setBillingPaymentState((prev) => ({
      ...prev,
      paymentMethod:
        selectedOrderBy === 'marketplace' ? 'OTA' : prev.paymentMethod,
    }))
  }, [selectedOrderBy])

  // Comprehensive validation system - validate current step when dependencies change
  useEffect(() => {
    setDisabledNext(!isStepValid(currentStep))
  }, [
    isStepValid,
    selectedOrderBy,
    selectedAgent,
    currentStep,
    tourPackageState,
    billingFormRef.current?.formState.errors,
  ])

  return (
    <Stepper
      totalSteps={
        selectedOrderBy === 'marketplace'
          ? MARKETPLACE_TOTAL_STEPS
          : TOTAL_STEPS
      }
      step={currentStep}
    >
      <Stepper.Indicators
        className="mx-auto"
        labels={stepLabels}
        icons={stepIcons}
      />

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

        {/* Choose Package */}
        <div className="my-12" ref={choosePackageRef}>
          <TourPackageProductList
            selectedAgent={selectedAgent}
            tourPackageProducts={props.tourPackageProducts}
            selectedTourPackageProduct={tourPackageState.selectedProduct}
            onChoose={handleChoosePackage}
          />
        </div>

        {/* Booking Details */}
        <div className="my-12">
          <BookingDetail
            selectedAgent={selectedAgent}
            harborTransferProducts={props.harborTransferProducts.data}
            tourPackageState={tourPackageState}
            ref={bookingDetailRef}
            orderBy={selectedOrderBy}
            onChangeTourPackageState={(state) => {
              setTourPackageState((prev) => ({
                ...prev,
                ...state,
              }))
            }}
          />
        </div>

        {/* Billing Details */}
        {selectedOrderBy === 'marketplace' && (
          <div className="my-12 grid grid-cols-12 gap-4 lg:gap-8 space-y-8">
            <div className="col-span-12 lg:col-span-5 space-y-4">
              <OrderSummary />
            </div>

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

              {/* Booking Policies */}
              {cart.order_by !== 'marketplace' && (
                <div className="w-full min-w-0">
                  <BookingPolicies
                    refundable={refundable}
                    reschedulable={reschedulable}
                    onRefundableChange={setRefundable}
                    onReschedulableChange={setReschedulable}
                  />
                </div>
              )}
            </div>
          </div>
        )}
      </Stepper.Content>

      {currentStep === Step.BookingDetails &&
      selectedOrderBy !== 'marketplace' ? (
        <Stepper.Navigation
          showStepCount
          disabled={disabledNext || submitting}
          nextButtonHandler={handleAddToCart}
          prevButtonHandler={goToPrevious}
          nextButtonType="submit"
          nextIcon={<LuShoppingCart className="h-5 w-5 ml-2" />}
          nextLabel="Add to Cart"
        />
      ) : currentStep === Step.BillingDetails ? (
        <Stepper.Navigation
          showStepCount
          disabled={disabledNext || submitting || processing}
          nextButtonHandler={processBooking}
          prevButtonHandler={goToPrevious}
          nextButtonType="submit"
          nextIcon={null}
          nextLabel="Process Booking"
        />
      ) : currentStep === Step.OrderPlacedBy ? (
        <Stepper.Navigation
          showStepCount
          enablePrev
          disabled={disabledNext || submitting}
          nextButtonHandler={goToNext}
          prevLabel="Service Selection"
          prevButtonHandler={() => {
            props.setSelectedServiceType(null)
          }}
        />
      ) : (
        <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>
  )
}
