'use client'

import React, { useRef, useState } from 'react'
import { LuShoppingCart, LuCreditCard, LuShieldCheck } from 'react-icons/lu'
import { toast } from 'react-toastify'
import { useRouter } from 'next/navigation'

import { useMerchant } from '@/lib/context/MerchantContext'
import { useCart } from '@/lib/context/CartContext'
import Stepper from '@/lib/components/stepper/Index'
import { scrollToRef } from '@/lib/utils/dom'
import { createOrder } from '@/lib/services/order-services'
import { handleApiError } from '@/lib/utils/error-handler'
import ConfirmationModal from '@/lib/components/modals/ConfirmationModal'
import { PAYMENT_METHOD_LABELS } from '@/lib/types/payment'
import PopupModal from '@/lib/components/modals/PopupModal'
import { usePopup } from '@/lib/hooks/usePopup'
import BillingPaymentForm, {
  BillingPaymentFormRef,
} from './billings/BillingPaymentForm'
import { BillingPaymentFormData } from './billings/schemas'
import BookingPolicies from './BookingPolicies'
import { CreateOrderPayload } from '../types'
import OrderSummary from './billings/OrderSummary'
import { IframeDataProps } from '@/lib/types/iframe'
import ModalIframe from '@/lib/components/modals/ModalIframe'
import ShoppingCart from './ShoppingCart'

interface CheckoutPageProps {
  shoppingCartRef: React.Ref<HTMLDivElement>
  onAddMoreItems: () => void
}

enum CheckoutStep {
  ShoppingCart = 0,
  Checkout = 1,
  Payment = 2,
}

const INITIAL_STEP = 0
const TOTAL_STEPS = 3

export default function Checkout({
  shoppingCartRef,
  onAddMoreItems,
}: CheckoutPageProps) {
  const router = useRouter()
  const { merchant } = useMerchant()
  const { cart, hasCartItems, prepareCartForCheckout, clearCart } = useCart()
  const { popup, showPopup, hidePopup } = usePopup()

  // Iframe States
  const [iframeData, setIframeData] = useState<IframeDataProps>({
    title: '',
    url: '',
  })
  const [isIframeModalOpened, setIsIframeModalOpened] = useState(false)

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

  // State
  const [currentStep, setCurrentStep] = useState(INITIAL_STEP)
  const [submitting, setSubmitting] = useState(false)
  const [showConfirmation, setShowConfirmation] = useState(false)

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

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

  const stepLabels = ['Shopping Cart', 'Checkout', 'Payment']
  const stepIcons = [
    <LuShoppingCart key="shopping-cart" className="h-5 w-5" />,
    <LuShieldCheck key="checkout" className="h-5 w-5" />,
    <LuCreditCard key="payment" className="h-5 w-5" />,
  ]

  // Navigation handlers
  const goToPrevious = () => {
    if (currentStep === CheckoutStep.Checkout) {
      setCurrentStep(CheckoutStep.ShoppingCart)
      scrollToRef(mainContentRef)
    }
  }

  const goToNext = () => {
    if (currentStep === CheckoutStep.ShoppingCart) {
      setCurrentStep(CheckoutStep.Checkout)
      scrollToRef(mainContentRef)
    }
  }

  const getBillingInformation = (billingData?: BillingPaymentFormData) => {
    if (
      billingData?.paymentMethod === 'PAY_ON_ARRIVAL' ||
      billingData?.paymentMethod === 'EDC' ||
      billingData?.paymentMethod === 'CASH'
    ) {
      switch (cart.order_by) {
        case 'agent':
          return {
            billing_name: billingData.billingName,
            billing_email: billingData.billingEmail,
            billing_phone: billingData.billingPhone ?? null,
          }
        case 'direct_guest':
          return {
            billing_name: billingData.billingName,
            billing_email: billingData.billingEmail,
            billing_phone: billingData.billingPhone,
          }
        default:
          return {}
      }
    }
  }

  // Checkout handler
  const handleCheckout = async () => {
    if (
      ['CASH', 'EDC', 'PAY_ON_ARRIVAL'].includes(
        billingPaymentState.paymentMethod || '',
      )
    ) {
      setShowConfirmation(true)
      return
    }

    await processCheckout()
  }

  const handleConfirmCheckout = async () => {
    await processCheckout()
  }

  async function processCheckout() {
    try {
      setSubmitting(true)

      const billingData = billingFormRef.current?.getValues()

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

      const checkoutPayload: CreateOrderPayload = {
        ...orderPayload,
        ...getBillingInformation(billingData),
        payment_method_code: billingData?.paymentMethod,
        booking_source:
          cart.order_by === 'direct_guest' ? billingData?.bookingSource : 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,
      })

      setShowConfirmation(false)

      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) {
      setShowConfirmation(false)

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

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

      <Stepper.Content ref={mainContentRef}>
        {/* Shopping Cart Step */}
        <div className="my-12 space-y-6">
          <ShoppingCart
            ref={shoppingCartRef}
            onAddMoreItems={onAddMoreItems}
            setIframeData={setIframeData}
            setIsIframeModalOpened={setIsIframeModalOpened}
          />
        </div>

        {/* Checkout & Payment Step */}
        <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={cart.order_by as OrderByType}
              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 === CheckoutStep.ShoppingCart ? (
        <Stepper.Navigation
          showStepCount
          enablePrev
          disabled={!hasCartItems()}
          nextButtonHandler={goToNext}
          prevButtonHandler={onAddMoreItems}
          prevLabel="Add More Items"
          nextLabel="Proceed to Checkout"
        />
      ) : (
        <Stepper.Navigation
          showStepCount
          disabled={!isBillingPaymentValid || submitting}
          nextButtonHandler={handleCheckout}
          prevButtonHandler={goToPrevious}
          nextButtonType="submit"
          nextIcon={null}
          nextLabel="Process Booking"
        />
      )}

      <ConfirmationModal
        isOpen={showConfirmation}
        onConfirm={handleConfirmCheckout}
        onClose={() => setShowConfirmation(false)}
        title={`Process Booking with ${PAYMENT_METHOD_LABELS[billingPaymentState.paymentMethod as keyof typeof PAYMENT_METHOD_LABELS]} Payment Method`}
        message={
          billingPaymentState.paymentMethod === 'PAY_ON_ARRIVAL'
            ? 'By processing the booking, cod-voucher will be automatically sent to customer.'
            : 'By processing the booking, e-ticket and invoice will be automatically sent to customer.'
        }
        confirmText="Process"
        loading={submitting}
      />

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

      <ModalIframe
        isIframeModalOpen={isIframeModalOpened}
        title={iframeData?.title}
        url={iframeData?.url}
        setIsIframeModalOpen={setIsIframeModalOpened}
      />
    </Stepper>
  )
}
