'use client'

import React, { useEffect, useMemo, useState } from 'react'
import { Button } from 'flowbite-react'
import { toast } from 'react-toastify'
import { useRouter, useSearchParams } from 'next/navigation'

import { useMerchant } from '@/lib/context/MerchantContext'
import { paginationDefaultData } from '@/lib/data/pagination'
import Pagination from '@/lib/components/Pagination'
import { constructSearchURL } from '@/lib/utils/url'
import * as PaginationConstant from '@/lib/constants/pagination'
import buttonTheme from '@/lib/themes/button'
import * as tourPackageSalesServices from '@/lib/services/tour-package-sales-services'
import { PaymentMethodCode } from '@/lib/types/payment'
import { BookingMethod, TourPackageOrder } from '../orders/types'
import { SearchFormProps } from './types'
import SearchForm from './partials/SearchForm'
import DataTable from './partials/DataTable'
import CreateReportModal from './partials/CreateReportModal'
import { Marketplace } from '@/app/(dashboard)/marketplaces/types'
import { getMarketplaces } from '@/lib/services/marketplace-services'
import { handleApiError } from '@/lib/utils/error-handler'
import { useAuth } from '@/lib/context/AuthContext'

export default function MainContent() {
  const router = useRouter()
  const { merchant } = useMerchant()
  const { user, userManagedMerchants } = useAuth()
  const searchParams = useSearchParams()
  const [reportModal, setReportModal] = useState<ModalState>({
    isOpened: false,
    type: 'create',
  })
  const [isLoadingInitial, setIsLoadingInitial] = useState(false)
  const [refreshTrigger, setRefreshTrigger] = useState(0)
  const [tourPackageSales, setTourPackageSales] = useState<
    Pagination<TourPackageOrder>
  >(paginationDefaultData)
  const [marketplaces, setMarketplaces] = useState<Marketplace[]>([])

  const searchParamsState: SearchFormProps['params'] = useMemo(
    () => ({
      invoiceNumber: searchParams.get('invoiceNumber') || '',
      bookingCode: searchParams.get('bookingCode') || '',
      startDate: searchParams.get('startDate') || '',
      endDate: searchParams.get('endDate') || '',
      startBookingDate: searchParams.get('startBookingDate') || '',
      endBookingDate: searchParams.get('endBookingDate') || '',
      paymentMethod:
        (searchParams.get('paymentMethod') as PaymentMethodCode) || '',
      refunded: searchParams.get('refunded') || '',
      bookingMethod: (searchParams.get('bookingMethod') as BookingMethod) || '',
      page: searchParams.get('page') ? Number(searchParams.get('page')) : 1,
      limit: searchParams.get('limit')
        ? Number(searchParams.get('limit'))
        : PaginationConstant.MIN_DATA_PER_PAGE,
      agentId: searchParams.get('agentId')
        ? Number(searchParams.get('agentId'))
        : '',
      marketplaceId: searchParams.get('marketplaceId')
        ? Number(searchParams.get('marketplaceId'))
        : '',
      partnerId: searchParams.get('partnerId')
        ? Number(searchParams.get('partnerId'))
        : '',
      orderPlacedBy: (searchParams.get('orderPlacedBy') as OrderByType) || '',
    }),
    [searchParams],
  )

  const [searchForm, setSearchForm] = useState<SearchFormProps>({
    searching: false,
    params: searchParamsState,
  })

  async function handleSearchSubmit(e?: React.FormEvent) {
    e?.preventDefault()

    setSearchForm((prev) => ({ ...prev, searching: true }))
    setTourPackageSales(paginationDefaultData)

    const newUrl = constructSearchURL(
      `/merchant-dashboard/${merchant?.id}/tour-package-sales`,
      {
        ...searchForm.params,
        page: 1,
      },
    )

    // Check if the URL would be the same (search with same parameters)
    const currentUrl = `${window.location.pathname}${window.location.search}`

    if (currentUrl === newUrl) {
      // If URL is the same, trigger a refresh instead of navigation
      setRefreshTrigger((prev) => prev + 1)
      return
    }

    return router.push(newUrl)
  }

  async function handlePageChange(page: number) {
    if (isNaN(page)) {
      setSearchForm((prev) => ({
        ...prev,
        params: {
          ...prev.params,
          page: 1,
        },
      }))

      // Directly pass the updated state value
      return router.push(
        constructSearchURL(
          `/merchant-dashboard/${merchant?.id}/tour-package-sales`,
          {
            ...searchForm.params,
            page: 1,
          },
        ),
      )
    }

    setSearchForm((prev) => ({
      ...prev,
      params: {
        ...prev.params,
        page,
      },
    }))

    // Directly pass the updated state value
    return router.push(
      constructSearchURL(
        `/merchant-dashboard/${merchant?.id}/tour-package-sales`,
        {
          ...searchForm.params,
          page,
        },
      ),
    )
  }

  function handleLimitChange(limit: number) {
    if (isNaN(Number(limit))) {
      setSearchForm((prev) => ({
        ...prev,
        params: {
          ...prev.params,
          page: 1,
          limit: PaginationConstant.MIN_DATA_PER_PAGE,
        },
      }))

      // Direct pass the updated state value
      return router.push(
        constructSearchURL(
          `/merchant-dashboard/${merchant?.id}/tour-package-sales`,
          {
            ...searchForm.params,
            page: 1,
            limit: PaginationConstant.MIN_DATA_PER_PAGE,
          },
        ),
      )
    }

    limit =
      Number(limit) < PaginationConstant.MIN_DATA_PER_PAGE ||
      Number(limit) > PaginationConstant.MAX_DATA_PER_PAGE
        ? PaginationConstant.MIN_DATA_PER_PAGE
        : limit

    setSearchForm((prev) => ({
      ...prev,
      params: {
        ...prev.params,
        page: 1,
        limit,
      },
    }))

    // Direct pass the updated state value
    return router.push(
      constructSearchURL(
        `/merchant-dashboard/${merchant?.id}/tour-package-sales`,
        {
          ...searchForm.params,
          page: 1,
          limit,
        },
      ),
    )
  }

  useEffect(() => {
    setIsLoadingInitial(true)

    tourPackageSalesServices
      .getAllTourPackageSales({
        merchantId: merchant?.id as number,
        params: searchParamsState,
      })
      .then(setTourPackageSales)
      .catch(() => {
        toast.error('Failed to load tour package sales. Please try again.')
      })
      .finally(() => {
        setIsLoadingInitial(false)
        setSearchForm((prev) => ({ ...prev, searching: false }))
      })
  }, [searchParamsState, refreshTrigger, merchant])

  useEffect(() => {
    const fetchMarketplaces = async () => {
      try {
        const marketplaces = await getMarketplaces({ all: true })
        setMarketplaces(marketplaces as Marketplace[])
      } catch (error) {
        handleApiError(error, 'Failed to load marketplaces. Please try again.')
      }
    }

    fetchMarketplaces()
  }, [])

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

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

  return (
    <section className="mt-8">
      <div>
        <h1 className="text-3xl font-semibold text-black mb-2">
          Tour Package Sales
        </h1>
        <p className="font-medium text-slate-500">
          Following are the list of tour package sales. You can manage them
          here.
        </p>

        <Button
          theme={buttonTheme.button}
          color="green"
          className="mt-4"
          onClick={() => {
            setReportModal({ isOpened: true, type: 'create' })
          }}
        >
          Create Report
        </Button>
      </div>

      <SearchForm
        marketplaces={marketplaces}
        searchForm={searchForm}
        setSearchForm={setSearchForm}
        handleSearch={handleSearchSubmit}
      />

      <DataTable
        tourPackageSales={tourPackageSales.data}
        isLoading={isLoadingInitial}
      />

      <CreateReportModal
        marketplaces={marketplaces}
        reportModal={reportModal}
        setReportModal={setReportModal}
      />

      <Pagination
        currentPage={tourPackageSales.current_page}
        from={tourPackageSales.from}
        to={tourPackageSales.to}
        lastPage={tourPackageSales.last_page}
        total={tourPackageSales.total}
        limit={searchForm.params.limit}
        handleLimitChange={handleLimitChange}
        handlePageChange={handlePageChange}
      />
    </section>
  )
}
