"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { Download } from "lucide-react"
import * as ExcelJS from 'exceljs'

import { Button } from "@/components/ui/button"
import { ContactPossibleItemDetail } from "../service"

interface ContactPossibleItemsTableToolbarActionsProps {
  table: Table<ContactPossibleItemDetail>
}

export function ContactPossibleItemsTableToolbarActions({
  table,
}: ContactPossibleItemsTableToolbarActionsProps) {

  const handleExport = () => {
    // 현재 테이블의 모든 데이터를 Excel로 내보내기
    const data = table.getFilteredRowModel().rows.map(row => ({
      "벤더 코드": row.original.vendorCode,
      "벤더명": row.original.vendorName,
      "벤더 국가": row.original.vendorCountry,
      "벤더 타입": row.original.techVendorType,
      "담당자명": row.original.contactName,
      "담당자 직책": row.original.contactPosition,
      "담당자 이메일": row.original.contactEmail,
      "담당자 전화번호": row.original.contactPhone,
      "담당자 국가": row.original.contactCountry,
      "주담당자": row.original.isPrimary ? "예" : "아니오",
      "아이템 코드": row.original.itemCode,
      "아이템명": row.original.itemList,
      "공종": row.original.workType,
      "선종": row.original.shipTypes,
      "서브아이템": row.original.subItemList,
      "생성일": new Date(row.original.createdAt).toLocaleDateString("ko-KR"),
      "수정일": new Date(row.original.updatedAt).toLocaleDateString("ko-KR"),
    }))

    downloadExcel(data, "contact_possible_items.xlsx")
  }

  return (
    <div className="flex items-center gap-2">
      <Button
        variant="outline"
        size="sm"
        onClick={handleExport}
      >
        <Download className="mr-2 h-4 w-4" />
        Excel 내보내기
      </Button>
    </div>
  )
}

// Excel 파일 다운로드
function downloadExcel(data: Array<Record<string, unknown>>, filename: string) {
  const workbook = new ExcelJS.Workbook()
  const worksheet = workbook.addWorksheet("Data")

  if (data.length > 0) {
    // 헤더 추가
    const headers = Object.keys(data[0])
    worksheet.addRow(headers)

    // 데이터 추가
    data.forEach(row => {
      worksheet.addRow(Object.values(row))
    })

    // 스타일 적용
    worksheet.getRow(1).font = { bold: true }
    worksheet.columns.forEach(column => {
      column.width = 15
    })
  }

  // 파일 다운로드
  workbook.xlsx.writeBuffer().then(buffer => {
    const blob = new Blob([buffer], { 
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" 
    })
    const url = window.URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    a.download = filename
    a.click()
    window.URL.revokeObjectURL(url)
  })
} 