'use client'

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

import CopyLink from '@/lib/components/CopyLink'
import { useMerchant } from '@/lib/context/MerchantContext'
import buttonTheme from '@/lib/themes/button'
import * as PaginationConstant from '@/lib/constants/pagination'
import { getRefunds } from '@/lib/services/refund-services'
import { paginationDefaultData } from '@/lib/data/pagination'
import { constructSearchURL } from '@/lib/utils/url'
import Pagination from '@/lib/components/Pagination'
import SearchForm from './partials/SearchForm'
import { Refund, RefundStatus, SearchFormProps } from './types'
import DataTable from './partials/DataTable'
import CreateReportModal from './partials/CreateReportModal'
import appConfig from '@/lib/config/app'
import { useRefundBroadcast } from '@/lib/hooks/useRefundBroadcast'
import { useAuth } from '@/lib/context/AuthContext'
import { FollowUpStatus } from '@/lib/constants/follow-up'

export default function MainContent() {
  const { merchant } = useMerchant()
  const router = useRouter()
  const searchParams = useSearchParams()
  const { user, userManagedMerchants } = useAuth()
  const [refreshTrigger, setRefreshTrigger] = useState(0)
  const [isLoadingInitial, setIsLoadingInitial] = useState(false)
  const [reportModal, setReportModal] = useState<ModalState>({
    type: 'create',
    isOpened: false,
  })
  const [refunds, setRefunds] = useState<Pagination<Refund>>(
    paginationDefaultData,
  )
  const [searchForm, setSearchForm] = useState<SearchFormProps>({
    searching: false,
    params: {
      status: (searchParams.get('status') as RefundStatus) || '',
      followUpStatus:
        (searchParams.get('followUpStatus') as FollowUpStatus) || null,
      followUpRatingId: searchParams.get('followUpRatingId')
        ? Number(searchParams.get('followUpRatingId'))
        : undefined,
      startDate: searchParams.get('startDate') || '',
      endDate: searchParams.get('endDate') || '',
      invoiceNumber: searchParams.get('invoiceNumber') || '',
      page: searchParams.get('page') ? Number(searchParams.get('page')) : 1,
      limit: searchParams.get('limit')
        ? Number(searchParams.get('limit'))
        : PaginationConstant.MIN_DATA_PER_PAGE,
    },
  })

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

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

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

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

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

  useEffect(() => {
    setIsLoadingInitial(true)

    getRefunds({
      merchantId: merchant?.id as number,
      params: {
        invoiceNumber: searchParams.get('invoiceNumber') || '',
        startDate: searchParams.get('startDate') || '',
        endDate: searchParams.get('endDate') || '',
        status: (searchParams.get('status') as RefundStatus) || '',
        followUpStatus:
          (searchParams.get('followUpStatus') as FollowUpStatus) || null,
        followUpRatingId: searchParams.get('followUpRatingId')
          ? Number(searchParams.get('followUpRatingId'))
          : undefined,
        page: Number(searchParams.get('page') ?? 1),
        limit: Number(
          searchParams.get('limit') ?? PaginationConstant.MIN_DATA_PER_PAGE,
        ),
      },
    })
      .then(setRefunds)
      .finally(() => {
        setIsLoadingInitial(false)
        setSearchForm((prev) => ({ ...prev, searching: false }))
      })
  }, [searchParams, refreshTrigger, merchant])

  // Listen to all refund events for real-time updates
  useRefundBroadcast({
    onRefundRequested: (data) => {
      if (!userManagedMerchants.includes(data.merchantId)) return
      setRefreshTrigger((prev) => prev + 1)
    },
    onRefundApproved: (data) => {
      if (!userManagedMerchants.includes(data.merchantId)) return
      setRefreshTrigger((prev) => prev + 1)
    },
    onRefundRejected: (data) => {
      if (!userManagedMerchants.includes(data.merchantId)) return
      setRefreshTrigger((prev) => prev + 1)
    },
  })

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

        {/* Action Buttons */}
        <div className="flex items-center gap-2 mt-4">
          <Button
            theme={buttonTheme.button}
            color="green"
            onClick={() => {
              setReportModal({ type: 'create', isOpened: true })
            }}
          >
            <span>Create Report</span>
          </Button>

          {user?.role !== 'supervisor' && (
            <Button
              theme={buttonTheme.button}
              color="default"
              as="a"
              href={`/merchant-dashboard/${merchant?.id}/refunds/create`}
            >
              Create Refund
            </Button>
          )}
        </div>

        <div className="max-w-fit mt-4">
          <CopyLink
            link={`${appConfig.frontendUrl}/${merchant?.username}/cancellation-requests`}
          />
        </div>
      </div>

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

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

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

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