"use client"

import { TrendingUp } from "lucide-react"
import { Suspense } from "react"

import { ListPageCard } from "@/app/dashboard/_components"
import { XmlApiErrorBanner } from "@/components/xml-apis/shared/xml-api-error-banner"
import { XrateXmlUploadTable } from "@/components/xml-apis/xrate-xml-upload/components/xrate-xml-upload-table"
import { XrateXmlUploadToolbar } from "@/components/xml-apis/xrate-xml-upload/components/xrate-xml-upload-toolbar"
import { useXrateXmlUpload } from "@/components/xml-apis/xrate-xml-upload/hooks/use-xrate-xml-upload"
import type { XrateXmlUpload } from "@/components/xml-apis/xrate-xml-upload/types"
import { Skeleton } from "@/components/ui/skeleton"

type XrateXmlUploadListPageProps = {
  initialData?: XrateXmlUpload[]
  initialTotalCount?: number
  initialPage?: number
  initialPageSize?: number
  initialPageCount?: number
  initialErrorMessage?: string | null
}

function XrateXmlUploadListContent({
  initialData = [],
  initialTotalCount = 0,
  initialPage = 1,
  initialPageSize = 10,
  initialPageCount = 1,
  initialErrorMessage = null,
}: XrateXmlUploadListPageProps) {
  const {
    data,
    totalCount,
    page,
    pageSize,
    pageCount,
    isLoading,
    isRefreshing,
    refresh,
    goToPage,
    changePageSize,
    removeLocal,
    patchLocal,
  } = useXrateXmlUpload({
    initialData,
    initialTotalCount,
    initialPage,
    initialPageSize,
    initialPageCount,
  })

  return (
    <ListPageCard
      icon={TrendingUp}
      title="XRate XML Upload"
      description="Upload and manage exchange-rate XML files by bank. Import, filter, and delete records."
      breadcrumb={[
        { label: "XML API" },
        { label: "XRate XML Upload" },
      ]}
      actions={
        <XrateXmlUploadToolbar
          isRefreshing={isRefreshing}
          onRefresh={() => void refresh()}
        />
      }
    >
      <XmlApiErrorBanner message={initialErrorMessage} />
      <XrateXmlUploadTable
        data={data}
        totalCount={totalCount}
        page={page}
        pageSize={pageSize}
        pageCount={pageCount}
        isLoading={isLoading || isRefreshing}
        onDelete={removeLocal}
        onDeleteTemp={(id) => patchLocal(id, { inserted: false })}
        onPageChange={goToPage}
        onPageSizeChange={changePageSize}
      />
    </ListPageCard>
  )
}

export function XrateXmlUploadListPage(props: XrateXmlUploadListPageProps) {
  return (
    <Suspense fallback={<Skeleton className="h-64 w-full rounded-lg" />}>
      <XrateXmlUploadListContent {...props} />
    </Suspense>
  )
}
