'use client'

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

import buttonTheme from '@/lib/themes/button'
import * as PaginationConstant from '@/lib/constants/pagination'
import { PaymentMethodCode, PaymentStatus } from '@/lib/types/payment'
import { paginationDefaultData } from '@/lib/data/pagination'
import { useMerchant } from '@/lib/context/MerchantContext'
import Pagination from '@/lib/components/Pagination'
import * as orderServices from '@/lib/services/order-services'
import { constructSearchURL } from '@/lib/utils/url'
import SearchForm from './partials/SearchForm'
import { Order, SearchFormProps } from './types'
import DataTable from './partials/DataTable'
import CreateReportModal from './partials/CreateReportModal'
import EditPaymentModal from './partials/EditPaymentModal'
import appConfig from '@/lib/config/app'
import QRCodeModal from '@/lib/components/modals/QRCodeModal'
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 searchParams = useSearchParams()
  const [isLoadingInitial, setIsLoadingInitial] = useState(false)
  const [refreshTrigger, setRefreshTrigger] = useState(0)
  const [order, setOrder] = useState<Order | null>(null)
  const [paymentModal, setPaymentModal] = useState<ModalState>({
    type: 'edit',
    isOpened: false,
  })
  const [reportModal, setReportModal] = useState<ModalState>({
    isOpened: false,
    type: 'create',
  })
  const [paymentLinkModal, setPaymentLinkModal] = useState({
    isOpen: false,
    invoiceNumber: '',
  })
  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) || '',
      partnerId: searchParams.get('partnerId')
        ? Number(searchParams.get('partnerId'))
        : undefined,
      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,
      page: searchParams.get('page') ? Number(searchParams.get('page')) : 1,
      limit: searchParams.get('limit')
        ? Number(searchParams.get('limit'))
        : PaginationConstant.MIN_DATA_PER_PAGE,
    },
  })
  const { user, userManagedMerchants } = useAuth()

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

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

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

  useEffect(() => {
    setIsLoadingInitial(true)

    orderServices
      .getOrders({
        merchantId: merchant?.id as number,
        params: {
          bookingMethod: 'online',
          page: Number(searchParams.get('page') ?? 1),
          limit: Number(
            searchParams.get('limit') ?? PaginationConstant.MIN_DATA_PER_PAGE,
          ),
          orderBy: (searchParams.get('orderBy') as OrderByType) || '',
          partnerId: searchParams.get('partnerId')
            ? Number(searchParams.get('partnerId'))
            : undefined,
          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])

  // Order Broadcast Handlers
  useOrderBroadcast({
    onOrderPaid: (data) => {
      if (
        data.bookingMethod === 'online' ||
        userManagedMerchants.includes(data.merchantId)
      ) {
        setRefreshTrigger((prev) => prev + 1)
      }
    },
    onOrderPlaced: (data) => {
      if (
        data.bookingMethod === 'online' ||
        userManagedMerchants.includes(data.merchantId)
      ) {
        setRefreshTrigger((prev) => prev + 1)
      }
    },
    onPaymentFailed: (data) => {
      if (
        data.bookingMethod === 'online' ||
        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">Orders</h1>
        <p className="font-medium text-slate-500">
          Following are the list of orders. You can manage them here.
        </p>

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

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

      <DataTable
        orders={orders.data}
        searchForm={searchForm}
        isLoading={isLoadingInitial}
        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}
        />
      )}

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

      <EditPaymentModal
        order={order as Order}
        paymentModal={paymentModal}
        setPaymentModal={setPaymentModal}
        setOrders={setOrders}
        onChange={(order) => {
          setPaymentLinkModal(() => ({
            isOpen: true,
            invoiceNumber: order.invoice_number as string,
          }))
        }}
      />

      <QRCodeModal
        isOpen={paymentLinkModal.isOpen}
        onClose={() =>
          setPaymentLinkModal((prev) => ({ ...prev, isOpen: false }))
        }
        url={`${appConfig.frontendUrl}/${merchant?.username}/payments/${paymentLinkModal.invoiceNumber}`}
        title="Payment Detail 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>
  )
}
