"use client"

import * as React from "react"
import { type Table } from "@tanstack/react-table"
import { Download, FileDown, Database, Loader2 } from "lucide-react"
import * as ExcelJS from 'exceljs'
import { saveAs } from "file-saver"
import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

import { Item } from "@/db/schema/items"
import { DeleteItemsDialog } from "./delete-items-dialog"
import { AddItemDialog } from "./add-items-dialog"
import { exportItemTemplate } from "./item-excel-template"
import { ImportItemButton } from "./import-excel-button"
import { syncItemsFromCodeLists } from "@/lib/sedp/sync-package"

// 동기화 함수 import (실제 경로로 수정 필요)

interface ItemsTableToolbarActionsProps {
  table: Table<Item>
}

export function ItemsTableToolbarActions({ table }: ItemsTableToolbarActionsProps) {
  const [refreshKey, setRefreshKey] = React.useState(0)
  const [isSyncing, setIsSyncing] = React.useState(false)

  // 가져오기 성공 후 테이블 갱신
  const handleImportSuccess = () => {
    setRefreshKey(prev => prev + 1)
  }

  // 테이블 새로고침 함수
  const refreshTable = () => {
    setRefreshKey(prev => prev + 1)
    // 페이지 새로고침 또는 데이터 refetch 로직
    window.location.reload()
  }

  // 전체 프로젝트 동기화
  const handleSyncAllProjects = async () => {
    if (isSyncing) return

    setIsSyncing(true)
    const loadingToast = toast.loading("모든 프로젝트의 아이템을 동기화하는 중...")

    try {
      await syncItemsFromCodeLists()
      toast.dismiss(loadingToast)
      toast.success("모든 프로젝트의 아이템이 성공적으로 동기화되었습니다!")
      
      // 테이블 새로고침
      setTimeout(() => {
        refreshTable()
      }, 1000)
    } catch (error) {
      toast.dismiss(loadingToast)
      toast.error("동기화 중 오류가 발생했습니다: " + (error as Error).message)
      console.error("동기화 오류:", error)
    } finally {
      setIsSyncing(false)
    }
  }



  // Excel 내보내기 함수
  const exportTableToExcel = async (
    table: Table<any>,
    options: {
      filename: string;
      excludeColumns?: string[];
      sheetName?: string;
    }
  ) => {
    const { filename, excludeColumns = [], sheetName = "아이템 목록" } = options;
    
    // 워크북 생성
    const workbook = new ExcelJS.Workbook();
    workbook.creator = 'Item Management System';
    workbook.created = new Date();
    
    // 워크시트 생성
    const worksheet = workbook.addWorksheet(sheetName);
    
    // 테이블 데이터 가져오기
    const data = table.getFilteredRowModel().rows.map(row => row.original);
    
    // 테이블 헤더 가져오기
    const headers = table.getAllColumns()
      .filter(column => !excludeColumns.includes(column.id))
      .map(column => ({
        key: column.id,
        header: column.columnDef.header?.toString() || column.id
      }));
    
    // 컬럼 정의
    worksheet.columns = headers.map(header => ({
      header: header.header,
      key: header.key,
      width: 20 // 기본 너비
    }));
    
    // 스타일 적용
    const headerRow = worksheet.getRow(1);
    headerRow.font = { bold: true };
    headerRow.fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE0E0E0' }
    };
    headerRow.alignment = { vertical: 'middle', horizontal: 'center' };
    
    // 데이터 행 추가
    data.forEach(item => {
      const row: Record<string, any> = {};
      headers.forEach(header => {
        row[header.key] = item[header.key];
      });
      worksheet.addRow(row);
    });
    
    // 전체 셀에 테두리 추가
    worksheet.eachRow((row, rowNumber) => {
      row.eachCell((cell) => {
        cell.border = {
          top: { style: 'thin' },
          left: { style: 'thin' },
          bottom: { style: 'thin' },
          right: { style: 'thin' }
        };
      });
    });
    
    try {
      // 워크북을 Blob으로 변환
      const buffer = await workbook.xlsx.writeBuffer();
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      saveAs(blob, `${filename}.xlsx`);
      return true;
    } catch (error) {
      console.error("Excel 내보내기 오류:", error);
      return false;
    }
  }

  return (
    <div className="flex items-center gap-2">
      {/* 선택된 로우가 있으면 삭제 다이얼로그 */}
      {table.getFilteredSelectedRowModel().rows.length > 0 ? (
        <DeleteItemsDialog
          items={table
            .getFilteredSelectedRowModel()
            .rows.map((row) => row.original)}
          onSuccess={() => table.toggleAllRowsSelected(false)}
        />
      ) : null}

      {/* 새 아이템 추가 다이얼로그 */}
      {/* <AddItemDialog /> */}

      {/* Import 버튼 */}
      {/* <ImportItemButton onSuccess={handleImportSuccess} /> */}

      {/* 동기화 버튼 */}
      <Button 
        variant="outline" 
        size="sm" 
        className="gap-2"
        disabled={isSyncing}
        onClick={handleSyncAllProjects}
      >
        {isSyncing ? (
          <Loader2 className="size-4 animate-spin" aria-hidden="true" />
        ) : (
          <Database className="size-4" aria-hidden="true" />
        )}
        <span className="hidden sm:inline">
          {isSyncing ? "동기화 중..." : "동기화"}
        </span>
      </Button>

      {/* Export 드롭다운 메뉴 */}
      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button variant="outline" size="sm" className="gap-2">
            <Download className="size-4" aria-hidden="true" />
            <span className="hidden sm:inline">Export</span>
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end">
          <DropdownMenuItem
            onClick={() =>
              exportTableToExcel(table, {
                filename: "items",
                excludeColumns: ["select", "actions"],
                sheetName: "아이템 목록"
              })
            }
          >
            <FileDown className="mr-2 h-4 w-4" />
            <span>현재 데이터 내보내기</span>
          </DropdownMenuItem>
          <DropdownMenuItem onClick={() => exportItemTemplate()}>
            <FileDown className="mr-2 h-4 w-4" />
            <span>템플릿 다운로드</span>
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  )
}