'use client'

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

import * as PaginationConstant from '@/lib/constants/pagination'
import { PaymentMethodCode, PaymentStatus } from '@/lib/types/payment'
import { paginationDefaultData } from '@/lib/data/pagination'
import Pagination from '@/lib/components/Pagination'
import * as transactionServices from '@/lib/services/transaction-services'
import { constructSearchURL } from '@/lib/utils/url'
import { Transaction } from '@/lib/types/transaction'
import { useBroadcast } from '@/lib/hooks/useBroadcast'
import { useAuth } from '@/lib/context/AuthContext'
import SearchForm from './_partials/SearchForm'
import DataTable from './_partials/DataTable'
import { SearchFormProps } from './types'

export default function MainContent() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const [isLoadingInitial, setIsLoadingInitial] = useState(false)
  const [refreshTrigger, setRefreshTrigger] = useState(0)
  const [transactions, setTransactions] = useState<Pagination<Transaction>>(
    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,
      paymentMethod:
        (searchParams.get('paymentMethod') as PaymentMethodCode) || null,
      paymentStatus:
        (searchParams.get('paymentStatus') as PaymentStatus) || null,
      page: searchParams.get('page') ? Number(searchParams.get('page')) : 1,
      limit: searchParams.get('limit')
        ? Number(searchParams.get('limit'))
        : PaginationConstant.MIN_DATA_PER_PAGE,
    },
  })
  const { user } = useAuth()

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

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

    const newUrl = constructSearchURL('/transactions', {
      ...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) {
    setSearchForm((prev) => ({
      ...prev,
      params: {
        ...prev.params,
        page,
      },
    }))

    // Directly pass the updated state value
    return router.push(
      constructSearchURL('/transactions', {
        ...searchForm.params,
        page,
      }),
    )
  }

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

    // Direct pass the updated state value
    return router.push(
      constructSearchURL('/transactions', {
        ...searchForm.params,
        page: 1,
        limit,
      }),
    )
  }

  useEffect(() => {
    setIsLoadingInitial(true)

    transactionServices
      .getTransactions({
        page: Number(searchParams.get('page') ?? 1),
        limit: Number(
          searchParams.get('limit') ?? PaginationConstant.MIN_DATA_PER_PAGE,
        ),
        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,
      })
      .then(setTransactions)
      .finally(() => {
        setIsLoadingInitial(false)
        setSearchForm((prev) => ({ ...prev, searching: false }))
      })
  }, [searchParams, refreshTrigger])

  // Broadcast Handlers
  useBroadcast({
    partnerId: user?.id as number,
    onOrderPlaced: () => {
      setRefreshTrigger((prev) => prev + 1)
    },
  })

  return (
    <section className="mt-8">
      <div>
        <h1 className="text-3xl font-semibold text-black mb-2">Transactions</h1>
        <p className="font-medium text-slate-500">
          Following are the list of the transactions from your referrals.
        </p>
      </div>

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

      <DataTable
        transactions={transactions.data}
        searchForm={searchForm}
        isLoading={isLoadingInitial}
      />

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