'use client'

import React, { useEffect, useRef, useState } from 'react'
import { ActivityProduct } from '@/lib/types/product/activity'
import { useMerchant } from '@/lib/context/MerchantContext'
import { useCart } from '@/lib/context/CartContext'
import { getActivityProducts } from '@/lib/services/activity-services'
import { getCountries } from '@/lib/services/country-services'
import {
  getHarborTransferBanner,
  getHarborTransferProducts,
} from '@/lib/services/harbor-transfer-services'
import {
  HarborTransferBanner,
  HarborTransferProduct,
} from '@/lib/types/product/harbor-transfer'
import { FastboatRoute } from '@/lib/types/product/fastboat'
import { getFastboatRoutes } from '@/lib/services/fastboat-services'
import { TourPackageProduct } from '@/lib/types/product/tour-package'
import { getTourPackageProducts } from '@/lib/services/tour-package-services'
import { AgentData } from '@/app/(dashboard)/agents/types'
import { getAgents } from '@/lib/services/agent-services'
import ServiceTypeSelector, { ServiceType } from './steps/ServiceTypeSelector'
import BoatBooking from './steps/BoatBooking'
import PackageBooking from './steps/PackageBooking'
import ExperienceBooking from './steps/ExperienceBooking'
import Checkout from './steps/Checkout'
import FloatingCartButton from './steps/FloatingCartButton'
import {
  ActivityOrderPayload,
  FastboatOrderPayload,
  TourPackageOrderPayload,
} from './types'
import { scrollToRef } from '@/lib/utils/dom'
import { Marketplace } from '@/app/(dashboard)/marketplaces/types'
import { getMarketplaces } from '@/lib/services/marketplace-services'
import { useRouter } from 'next/navigation'
import { useAuth } from '@/lib/context/AuthContext'

export default function MainContent() {
  const router = useRouter()
  const { user, userManagedMerchants } = useAuth()
  const { merchant } = useMerchant()
  const { cart, addFastboatToCart, addActivityToCart, addTourPackageToCart } =
    useCart()
  const [showCheckout, setShowCheckout] = useState<boolean>(false)
  const shoppingCartRef = useRef<HTMLDivElement>(null)
  const serviceTypeSelectorRef = useRef<HTMLDivElement>(null)
  const [selectedServiceType, setSelectedServiceType] =
    useState<ServiceType | null>(null)
  const [activityProducts, setActivityProducts] = useState<{
    isLoading: boolean
    data: ActivityProduct[]
  }>({
    isLoading: true,
    data: [],
  })
  const [tourPackageProducts, setTourPackageProducts] = useState<{
    isLoading: boolean
    data: TourPackageProduct[]
  }>({
    isLoading: true,
    data: [],
  })
  const [countries, setCountries] = useState<{
    isLoading: boolean
    data: Country[]
  }>({
    isLoading: true,
    data: [],
  })
  const [harborTransferBanner, setHarborTransferBanner] = useState<{
    isLoading: boolean
    data: HarborTransferBanner | null
  }>({
    isLoading: true,
    data: null,
  })
  const [harborTransferProducts, setHarborTransferProducts] = useState<{
    isLoading: boolean
    data: HarborTransferProduct[]
  }>({
    isLoading: true,
    data: [],
  })
  const [fastboatRoutes, setFastboatRoutes] = useState<{
    isLoading: boolean
    data: FastboatRoute[]
  }>({
    isLoading: true,
    data: [],
  })
  const [agents, setAgents] = useState<{
    isLoading: boolean
    data: AgentData[]
  }>({
    isLoading: true,
    data: [],
  })
  const [marketplaces, setMarketplaces] = useState<{
    isLoading: boolean
    data: Marketplace[]
  }>({
    isLoading: true,
    data: [],
  })

  const handleAddBoatToCart = ({
    fastboatOrder,
    activityOrder,
    orderBy,
    agentId,
    marketplaceId,
  }: {
    fastboatOrder: FastboatOrderPayload
    activityOrder: ActivityOrderPayload | null
    orderBy: OrderByType
    agentId?: number
    marketplaceId?: number
  }) => {
    const success = addFastboatToCart({
      fastboatOrder,
      orderBy,
      agentId,
      marketplaceId,
    })

    if (!success) {
      return
    }

    if (activityOrder) {
      handleAddExperienceToCart({
        activityOrder,
        orderBy,
        agentId,
        marketplaceId,
      })

      return
    }

    setSelectedServiceType('boat_ticket')
    setShowCheckout(true)

    scrollToRef(shoppingCartRef)
  }

  const handleAddTourPackageToCart = ({
    tourPackageOrder,
    orderBy,
    agentId,
    marketplaceId,
  }: {
    tourPackageOrder: TourPackageOrderPayload
    orderBy: OrderByType
    agentId?: number
    marketplaceId?: number
  }) => {
    const success = addTourPackageToCart({
      tourPackageOrder,
      orderBy,
      agentId,
      marketplaceId,
    })

    if (!success) {
      return
    }

    setSelectedServiceType('tour_package')
    setShowCheckout(true)

    scrollToRef(shoppingCartRef)
  }

  const handleAddExperienceToCart = ({
    activityOrder,
    orderBy,
    agentId,
    marketplaceId,
  }: {
    activityOrder: ActivityOrderPayload
    orderBy: OrderByType
    agentId?: number
    marketplaceId?: number
  }) => {
    const success = addActivityToCart({
      activityOrder,
      orderBy,
      agentId,
      marketplaceId,
    })

    if (!success) {
      return
    }

    setSelectedServiceType('boat_ticket')
    setShowCheckout(true)

    scrollToRef(shoppingCartRef)
  }

  const handleViewCart = () => {
    setShowCheckout(true)
    setSelectedServiceType(null)
    scrollToRef(shoppingCartRef)
  }

  const handleAddMoreItems = () => {
    setShowCheckout(false)
    setSelectedServiceType(null)
    scrollToRef(serviceTypeSelectorRef)
  }

  useEffect(() => {
    if (merchant?.id) {
      async function fetchAllData() {
        try {
          const [
            activityProducts,
            countries,
            harborTransferBanner,
            harborTransferProducts,
            fastboatRoutes,
            tourPackageProducts,
            agents,
            marketplaces,
          ] = await Promise.all([
            getActivityProducts(merchant?.id as number),
            getCountries(),
            getHarborTransferBanner(merchant?.id as number),
            getHarborTransferProducts(merchant?.id as number),
            getFastboatRoutes(merchant?.id as number),
            getTourPackageProducts(merchant?.id as number),
            getAgents({ all: true }),
            getMarketplaces({ all: true }),
          ])

          setActivityProducts({ isLoading: false, data: activityProducts })
          setCountries({ isLoading: false, data: countries })
          setHarborTransferBanner({
            isLoading: false,
            data: harborTransferBanner,
          })
          setHarborTransferProducts({
            isLoading: false,
            data: harborTransferProducts,
          })
          setFastboatRoutes({ isLoading: false, data: fastboatRoutes })
          setTourPackageProducts({
            isLoading: false,
            data: tourPackageProducts,
          })
          setAgents({ isLoading: false, data: agents as AgentData[] })
          setMarketplaces({
            isLoading: false,
            data: marketplaces as Marketplace[],
          })
        } catch {
          setActivityProducts({ isLoading: false, data: [] })
          setCountries({ isLoading: false, data: [] })
          setHarborTransferBanner({ isLoading: false, data: null })
          setHarborTransferProducts({ isLoading: false, data: [] })
          setFastboatRoutes({ isLoading: false, data: [] })
          setTourPackageProducts({ isLoading: false, data: [] })
          setAgents({ isLoading: false, data: [] })
          setMarketplaces({ isLoading: false, data: [] })
        }
      }

      fetchAllData()
    }
  }, [merchant])

  // Authorize User
  useEffect(() => {
    // Make sure all necessary data is loaded before authorization check
    if (!user || !merchant || userManagedMerchants.length === 0) return

    if (
      user.role === 'accounting' ||
      !userManagedMerchants.includes(merchant.id as number)
    ) {
      router.replace('/')
    }
  }, [user, merchant, userManagedMerchants, router])

  return (
    <section className="my-8 max-w-7xl mx-auto">
      {!showCheckout && selectedServiceType === null && (
        <ServiceTypeSelector
          ref={serviceTypeSelectorRef}
          selectedServiceType={selectedServiceType}
          onServiceTypeChange={setSelectedServiceType}
        />
      )}

      {!showCheckout && selectedServiceType === 'boat_ticket' && (
        <BoatBooking
          activityProducts={activityProducts}
          agents={agents}
          marketplaces={marketplaces}
          countries={countries}
          harborTransferBanner={harborTransferBanner}
          harborTransferProducts={harborTransferProducts}
          fastboatRoutes={fastboatRoutes}
          setSelectedServiceType={setSelectedServiceType}
          onAddToCart={handleAddBoatToCart}
        />
      )}

      {!showCheckout && selectedServiceType === 'tour_package' && (
        <PackageBooking
          agents={agents}
          marketplaces={marketplaces}
          harborTransferProducts={harborTransferProducts}
          tourPackageProducts={tourPackageProducts}
          onAddToCart={handleAddTourPackageToCart}
          setSelectedServiceType={setSelectedServiceType}
        />
      )}

      {!showCheckout && selectedServiceType === 'experience' && (
        <ExperienceBooking
          agents={agents}
          marketplaces={marketplaces}
          activityProducts={activityProducts}
          onAddToCart={handleAddExperienceToCart}
          setSelectedServiceType={setSelectedServiceType}
        />
      )}

      {/* Checkout Page */}
      {showCheckout && (
        <Checkout
          shoppingCartRef={shoppingCartRef}
          onAddMoreItems={handleAddMoreItems}
        />
      )}

      {/* Floating Cart Button */}
      {!showCheckout &&
        cart.order_by !== 'merchant' &&
        cart.order_by !== 'marketplace' && (
          <FloatingCartButton onClick={handleViewCart} />
        )}
    </section>
  )
}
