"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { Download, RefreshCcw } from "lucide-react"

import { exportTableToExcel } from "@/lib/export"
import { Button } from "@/components/ui/button"
import { ExtendedTagClasses } from "../validation"
import { toast } from "sonner"

interface ItemsTableToolbarActionsProps {
  table: Table<ExtendedTagClasses>
}

export function EquipClassTableToolbarActions({ table }: ItemsTableToolbarActionsProps) {
  const [isLoading, setIsLoading] = React.useState(false)

  const syncObjectClasses = async () => {
    try {
      setIsLoading(true)

      // API 엔드포인트 호출
      const response = await fetch('/api/cron/object-classes')

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || 'Failed to sync object classes')
      }

      const data = await response.json()

      // 성공 메시지 표시
      toast.success(
        `object classes synced successfully! ${data.result.items} items processed.`
      )

      // 페이지 새로고침으로 테이블 데이터 업데이트
      window.location.reload()
    } catch (error) {
      console.error('Error syncing object classes:', error)
      toast.error(
        error instanceof Error
          ? error.message
          : 'An error occurred while syncing object classes'
      )
    } finally {
      setIsLoading(false)
    }
  }

  return (
    <div className="flex items-center gap-2">
      <Button
        variant="samsung"
        size="sm"
        className="gap-2"
        onClick={syncObjectClasses}
        disabled={isLoading}
      >
        <RefreshCcw className={`size-4 ${isLoading ? 'animate-spin' : ''}`} aria-hidden="true" />
        <span className="hidden sm:inline">
          {isLoading ? 'Syncing...' : 'Get Equip Class'}
        </span>
      </Button>

      {/** 4) Export 버튼 */}
      <Button
        variant="outline"
        size="sm"
        onClick={() =>
          exportTableToExcel(table, {
            filename: "Equip Class",
            excludeColumns: ["select", "actions"],
          })
        }
        className="gap-2"
      >
        <Download className="size-4" aria-hidden="true" />
        <span className="hidden sm:inline">Export</span>
      </Button>
    </div>
  )
}