'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 * as fastboatSalesServices from '@/lib/services/fastboat-sales-services'
import buttonTheme from '@/lib/themes/button'
import {
  getFastboatNames,
  getFastboatRoutes,
} from '@/lib/services/fastboat-services'
import { FastboatName, FastboatRoute } from '@/lib/types/product/fastboat'
import { PaymentMethodCode } from '@/lib/types/payment'
import { BookingMethod, FastboatOrder, Trip } from '../orders/types'
import { SearchFormProps } from './types'
import SearchForm from './partials/SearchForm'
import DataTable from './partials/DataTable'
import CreateReportModal from './partials/CreateReportModal'
import { Merchant } from '@/app/(dashboard)/merchants/types'
import { Marketplace } from '@/app/(dashboard)/marketplaces/types'
import { getMerchants } from '@/lib/services/merchant-services'
import { handleApiError } from '@/lib/utils/error-handler'
import { getMarketplaces } from '@/lib/services/marketplace-services'
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 [fastboatRoutes, setFastboatRoutes] = useState<FastboatRoute[]>([])
  const [fastboatSales, setFastboatSales] = useState<Pagination<FastboatOrder>>(
    paginationDefaultData,
  )
  const [fastboatNames, setFastboatNames] = useState<FastboatName[]>([])
  const [merchants, setMerchants] = useState<Merchant[]>([])
  const [marketplaces, setMarketplaces] = useState<Marketplace[]>([])

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

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

  // Fetch Fast boat names and routes of the current merchant
  useEffect(() => {
    if (!merchant) return

    getFastboatNames(merchant?.id).then(setFastboatNames)
    getFastboatRoutes(merchant?.id).then(setFastboatRoutes)
  }, [merchant])

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

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

    const newUrl = constructSearchURL(
      `/merchant-dashboard/${merchant?.id}/fastboat-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}/fastboat-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}/fastboat-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}/fastboat-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}/fastboat-sales`, {
        ...searchForm.params,
        page: 1,
        limit,
      }),
    )
  }

  useEffect(() => {
    setIsLoadingInitial(true)

    fastboatSalesServices
      .getAllFastboatSales({
        merchantId: merchant?.id as number,
        params: searchParamsState,
      })
      .then(setFastboatSales)
      .catch(() => {
        toast.error('Failed to load fast boat sales. Please try again.')
      })
      .finally(() => {
        setIsLoadingInitial(false)
        setSearchForm((prev) => ({ ...prev, searching: false }))
      })
  }, [refreshTrigger, merchant, searchParamsState])

  useEffect(() => {
    const fetchMerchants = async () => {
      try {
        const merchants = await getMerchants({ all: true })
        setMerchants(merchants as Merchant[])
      } catch (error) {
        handleApiError(error, 'Failed to load merchants. Please try again.')
      }
    }

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

    Promise.allSettled([fetchMarketplaces(), fetchMerchants()])
  }, [])

  // 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">
          Fast Boat Sales
        </h1>
        <p className="font-medium text-slate-500">
          Following are the list of fast boat 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
        merchants={merchants}
        marketplaces={marketplaces}
        fastboatRoutes={fastboatRoutes}
        fastboatNames={fastboatNames}
        searchForm={searchForm}
        setSearchForm={setSearchForm}
        handleSearch={handleSearchSubmit}
      />

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

      <CreateReportModal
        merchants={merchants}
        marketplaces={marketplaces}
        fastboatRoutes={fastboatRoutes}
        fastboatNames={fastboatNames}
        reportModal={reportModal}
        setReportModal={setReportModal}
      />

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