'use client'

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

import { useMerchant } from '@/lib/context/MerchantContext'
import buttonTheme from '@/lib/themes/button'
import * as PaginationConstant from '@/lib/constants/pagination'
import { paginationDefaultData } from '@/lib/data/pagination'
import { constructSearchURL } from '@/lib/utils/url'
import { getOrders } from '@/lib/services/order-services'
import { PaymentMethodCode, PaymentStatus } from '@/lib/types/payment'
import Pagination from '@/lib/components/Pagination'
import SearchForm from './partials/SearchForm'
import { SearchFormProps } from './types'
import { Order } from '../orders/types'
import DataTable from './partials/DataTable'
import EditPaymentModal from './partials/EditPaymentModal'
import CreateReportModal from './partials/CreateReportModal'
import QRCodeModal from '@/lib/components/modals/QRCodeModal'
import appConfig from '@/lib/config/app'
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 { useOrderBroadcast } from '@/lib/hooks/useOrderBroadcast'
import { useAuth } from '@/lib/context/AuthContext'
import { FollowUpStatus } from '@/lib/constants/follow-up'

export default function MainContent() {
  const router = useRouter()
  const { merchant } = useMerchant()
  const { user, userManagedMerchants } = useAuth()
  const searchParams = useSearchParams()
  const [order, setOrder] = useState<Partial<Order>>({})
  const [isLoadingInitial, setIsLoadingInitial] = useState(false)
  const [refreshTrigger, setRefreshTrigger] = useState(0)
  const [paymentModal, setPaymentModal] = useState<ModalState>({
    type: 'edit',
    isOpened: false,
  })
  const [merchants, setMerchants] = useState<Merchant[]>([])
  const [marketplaces, setMarketplaces] = useState<Marketplace[]>([])
  const [paymentLinkModal, setPaymentLinkModal] = useState<
    ModalState<{ order: Partial<Order> }>
  >({
    isOpened: false,
    type: 'info',
  })
  const [orders, setOrders] = useState<Pagination<Order>>(paginationDefaultData)
  const [searchForm, setSearchForm] = useState<SearchFormProps>({
    searching: false,
    params: {
      billingName: searchParams.get('billingName') || '',
      invoiceNumber: searchParams.get('invoiceNumber') || '',
      startDate: searchParams.get('startDate') || null,
      endDate: searchParams.get('endDate') || null,
      orderBy: (searchParams.get('orderBy') as OrderByType) || '',
      paymentMethod:
        (searchParams.get('paymentMethod') as PaymentMethodCode) || null,
      paymentStatus:
        (searchParams.get('paymentStatus') as PaymentStatus) || null,
      followUpStatus:
        (searchParams.get('followUpStatus') as FollowUpStatus) || null,
      followUpRatingId: searchParams.get('followUpRatingId')
        ? Number(searchParams.get('followUpRatingId'))
        : undefined,
      agentId: searchParams.get('agentId')
        ? Number(searchParams.get('agentId'))
        : undefined,
      merchantId: searchParams.get('merchantId')
        ? Number(searchParams.get('merchantId'))
        : undefined,
      marketplaceId: searchParams.get('marketplaceId')
        ? Number(searchParams.get('marketplaceId'))
        : undefined,
      partnerId: searchParams.get('partnerId')
        ? Number(searchParams.get('partnerId'))
        : undefined,
      page: searchParams.get('page') ? Number(searchParams.get('page')) : 1,
      limit: searchParams.get('limit')
        ? Number(searchParams.get('limit'))
        : PaginationConstant.MIN_DATA_PER_PAGE,
    },
  })
  const [reportModal, setReportModal] = useState<ModalState>({
    isOpened: false,
    type: 'create',
  })

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

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

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

  useEffect(() => {
    setIsLoadingInitial(true)

    getOrders({
      merchantId: merchant?.id as number,
      params: {
        bookingMethod: 'offline',
        page: Number(searchParams.get('page') ?? 1),
        limit: Number(
          searchParams.get('limit') ?? PaginationConstant.MIN_DATA_PER_PAGE,
        ),
        agentId: searchParams.get('agentId')
          ? Number(searchParams.get('agentId'))
          : undefined,
        merchantId: searchParams.get('merchantId')
          ? Number(searchParams.get('merchantId'))
          : undefined,
        marketplaceId: searchParams.get('marketplaceId')
          ? Number(searchParams.get('marketplaceId'))
          : undefined,
        partnerId: searchParams.get('partnerId')
          ? Number(searchParams.get('partnerId'))
          : undefined,
        orderBy: (searchParams.get('orderBy') as OrderByType) || '',
        billingName: searchParams.get('billingName') || '',
        invoiceNumber: searchParams.get('invoiceNumber') || '',
        startDate: searchParams.get('startDate') || '',
        endDate: searchParams.get('endDate') || '',
        paymentMethod: (searchParams.get('paymentMethod') ||
          '') as PaymentMethodCode,
        paymentStatus: (searchParams.get('paymentStatus') ||
          '') as PaymentStatus,
        followUpStatus:
          (searchParams.get('followUpStatus') as FollowUpStatus) || null,
        followUpRatingId: searchParams.get('followUpRatingId')
          ? Number(searchParams.get('followUpRatingId'))
          : undefined,
      },
    })
      .then(setOrders)
      .finally(() => {
        setIsLoadingInitial(false)
        setSearchForm((prev) => ({ ...prev, searching: false }))
      })
  }, [searchParams, refreshTrigger, merchant])

  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()])
  }, [])

  // Order Broadcast Handlers
  useOrderBroadcast({
    onOrderPaid: (data) => {
      if (
        data.bookingMethod === 'offline' &&
        userManagedMerchants.includes(data.merchantId)
      ) {
        setRefreshTrigger((prev) => prev + 1)
      }
    },
    onPaymentFailed: (data) => {
      if (
        data.bookingMethod === 'offline' &&
        userManagedMerchants.includes(data.merchantId)
      ) {
        setRefreshTrigger((prev) => prev + 1)
      }
    },
  })

  // 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="mt-8">
      <div>
        <h1 className="text-3xl font-semibold text-black mb-2">
          Offline Bookings
        </h1>
        <p className="font-medium text-slate-500">
          Following are the list of transactions. You can manage them here.
        </p>

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

            <Button
              theme={buttonTheme.button}
              color="default"
              onClick={() => {
                router.push(
                  `/merchant-dashboard/${merchant?.id}/bookings/create`,
                )
              }}
            >
              Create Booking
            </Button>
          </div>
        )}
      </div>

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

      <DataTable
        isLoading={isLoadingInitial}
        searchForm={searchForm}
        orders={orders.data}
        setOrder={setOrder}
        setOrders={setOrders}
        setPaymentModal={setPaymentModal}
      />

      {!isLoadingInitial && (
        <Pagination
          currentPage={orders.current_page}
          lastPage={orders.last_page}
          limit={
            searchParams.get('limit') ? Number(searchParams.get('limit')) : 10
          }
          from={orders.from}
          to={orders.to}
          total={orders.total}
          handlePageChange={handlePageChange}
          handleLimitChange={handleLimitChange}
        />
      )}

      <EditPaymentModal
        order={order}
        onChange={(order) => {
          setPaymentLinkModal((prev) => ({
            ...prev,
            isOpened: true,
            data: {
              order,
            },
          }))
        }}
        paymentModal={paymentModal}
        setOrders={setOrders}
        setPaymentModal={setPaymentModal}
      />

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

      <QRCodeModal
        isOpen={paymentLinkModal.isOpened}
        onClose={() =>
          setPaymentLinkModal((prev) => ({ ...prev, isOpened: false }))
        }
        url={
          paymentLinkModal.data?.order.billing_name
            ? `${appConfig.frontendUrl}/${merchant?.username}/payments/${paymentLinkModal.data?.order.invoice_number}`
            : `${appConfig.frontendUrl}/${merchant?.username}/bookings/${paymentLinkModal.data?.order.invoice_number}/checkout`
        }
        title={
          paymentLinkModal.data?.order.billing_name
            ? 'Payment Detail Link'
            : 'Checkout Link'
        }
        successMessage="Link copied! Share it with your customer."
      >
        <div className="space-y-2">
          <p className="text-sm text-slate-600 font-medium">
            Scan the QR code to proceed with payment
          </p>
          <p className="text-xs text-slate-500">
            Or copy the link below to share it with your customer.
          </p>
        </div>
      </QRCodeModal>
    </section>
  )
}
