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

import { AgentData } from '@/app/(dashboard)/agents/types'
import { ActivityProduct } from '@/lib/types/product/activity'
import Stepper from '@/lib/components/stepper/Index'
import { scrollToRef } from '@/lib/utils/dom'
import { ServiceType } from './ServiceTypeSelector'
import PopupModal from '@/lib/components/modals/PopupModal'
import { usePopup } from '@/lib/hooks/usePopup'
import { ActivityOrderPayload, CreateOrderPayload } from '../types'
import OrderBySelector from './OrderBySelector'
import { AdjustablePriceData } from './experience-orders/types'
import ExperienceProductList from './experience-orders/ExperienceProductList'
import ExperienceBookingDetail from './experience-orders/ExperienceBookingDetail'
import { constructPayload } from './experience-orders/helpers'
import { BookingFormData } from './experience-orders/schemas'
import { Marketplace } from '@/app/(dashboard)/marketplaces/types'
import { useMerchant } from '@/lib/context/MerchantContext'
import { useCart } from '@/lib/context/CartContext'
import { useRouter } from 'next/navigation'
import BillingPaymentForm, {
  BillingPaymentFormRef,
} from './billings/BillingPaymentForm'
import { BillingPaymentFormData } from './billings/schemas'
import { createOrder } from '@/lib/services/order-services'
import { handleApiError } from '@/lib/utils/error-handler'
import OrderSummary from './billings/OrderSummary'
import BookingPolicies from './BookingPolicies'

interface ExperienceBookingProps {
  onAddToCart: ({
    activityOrder,
    orderBy,
    agentId,
  }: {
    activityOrder: ActivityOrderPayload
    orderBy: OrderByType
    agentId?: number
  }) => void
  activityProducts: {
    isLoading: boolean
    data: ActivityProduct[]
  }
  agents: {
    isLoading: boolean
    data: AgentData[]
  }
  marketplaces: {
    isLoading: boolean
    data: Marketplace[]
  }
  setSelectedServiceType: (type: ServiceType | null) => void
}

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

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

export interface ExperienceState {
  selectedProduct?: ActivityProduct | null
  adjustablePrices?: AdjustablePriceData[]
  bookingData?: BookingFormData | null
  isFormValid?: boolean
}

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

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

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

  // Experience States
  const [experienceState, setExperienceState] = useState<ExperienceState>({
    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)

  // 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 Experience',
    'Booking Details',
    'Billing Details',
  ]
  const stepIcons = [
    <LuUser key="order-placed-by" className="h-5 w-5" />,
    <LuMapPin key="choose-experience" 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.ChooseExperience:
        scrollToRef(chooseExperienceRef)
        break
      case Step.BookingDetails:
        scrollToRef(bookingDetailRef)
        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.ChooseExperience)
      handleScrollToRef(Step.ChooseExperience)
    }
  }

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

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

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

    if (agent && selectedOrderBy === 'agent') {
      setExperienceState((prev) => ({
        ...prev,
        selectedProduct: null,
        adjustablePrices: [],
        bookingData: null,
        isFormValid: false,
      }))

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

  // Stepper Handlers
  const goToPrevious = () => {
    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 activityOrderPayload = constructPayload({
          experienceState: {
            ...experienceState,
            includeExperience: true,
          },
          selectedOrderBy: selectedOrderBy as OrderByType,
        })

        addActivityToCart({
          activityOrder: activityOrderPayload as ActivityOrderPayload,
          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 !experienceState.isFormValid
        case Step.BillingDetails:
          if (selectedOrderBy === 'marketplace') {
            return !isBillingPaymentValid
          }

          return false
        default:
          return false
      }
    },
    [experienceState.isFormValid, 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.ChooseExperience:
          if (!experienceState.selectedProduct) {
            errors.push('Please select an experience product.')
          }
          break
      }

      return errors
    },
    [selectedAgent, selectedOrderBy, experienceState.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],
  )

  // Experience Handlers
  const handleChooseExperience = (product: ActivityProduct) => {
    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,
        }
      }) || []

    setExperienceState((prev) => ({
      ...prev,
      selectedProduct: product,
      adjustablePrices: mappedPrices,
      bookingData: null,
      isFormValid: false,
    }))

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

  // Handle state changes from the booking detail component
  const handleExperienceStateChange = (state: ExperienceState) => {
    setExperienceState((prev) => ({
      ...prev,
      ...state,
    }))
  }

  async function handleAddToCart() {
    setSubmitting(true)

    if (
      !experienceState.selectedProduct ||
      !experienceState.bookingData ||
      !experienceState.adjustablePrices
    ) {
      toast.error('Please complete all required fields.')
      setSubmitting(false)
      return
    }

    // Construct the activity order payload
    const activityOrderPayload = constructPayload({
      experienceState: {
        ...experienceState,
        includeExperience: true,
      },
      selectedOrderBy: selectedOrderBy as OrderByType,
    })

    props.onAddToCart({
      activityOrder: activityOrderPayload as ActivityOrderPayload,
      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,
    experienceState,
  ])

  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="experience"
            agents={props.agents}
            marketplaces={props.marketplaces}
            selectedOrderBy={selectedOrderBy}
            selectedAgent={selectedAgent}
            selectedMarketplace={selectedMarketplace}
            onOrderByChange={handleChangeOrderBy}
            onAgentChange={handleChangeAgent}
            onMarketplaceChange={handleChangeMarketplace}
          />
        </div>

        {/* Choose Experience */}
        <div className="my-12" ref={chooseExperienceRef}>
          <div className="space-y-12">
            <div className="space-y-2">
              <h2 className="text-2xl font-semibold">Choose Experience</h2>
              <p className="text-slate-500">
                Choose from the available experiences below.
              </p>
            </div>

            <ExperienceProductList
              selectedAgent={selectedAgent}
              activityProducts={props.activityProducts}
              selectedExperienceProduct={experienceState.selectedProduct}
              onChoose={handleChooseExperience}
            />
          </div>
        </div>

        {/* Booking Details */}
        <div className="my-12">
          <ExperienceBookingDetail
            ref={bookingDetailRef}
            experienceState={experienceState}
            orderBy={selectedOrderBy}
            selectedAgent={selectedAgent}
            onStateChange={handleExperienceStateChange}
          />
        </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>
  )
}
