'use client'

/**
 * 조달담당자 선택기
 * 
 * @description
 * - 오라클에서 CMCTB_CDNM, CMCTB_CD 테이블에서 CD_CLF = 'MMK010' 인 건들을 조회
 * - PROCUREMENT_MANAGER_CODE: 조달담당자 코드
 * - DISPLAY_NAME: 담당자명
 * - DEPARTMENT_NAME: 부서명
 * - EMPLOYEE_NUMBER: 사번
 * - 선택 시 사용자 정보도 함께 반환
 */

import { useState, useCallback, useMemo, useTransition } from 'react'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Search, Check } from 'lucide-react'
import { 
  ColumnDef,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
  SortingState,
  ColumnFiltersState,
  VisibilityState,
  RowSelectionState,
} from '@tanstack/react-table'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import { 
  getProcurementManagers, 
  addUsersToManagersAsync,
  ProcurementManager, 
  ProcurementManagerWithUser
} from './procurement-manager-service'
import { toast } from 'sonner'

export interface ProcurementManagerSelectorProps {
  selectedManager?: ProcurementManagerWithUser
  onManagerSelect: (manager: ProcurementManagerWithUser) => void
  disabled?: boolean
  placeholder?: string
  className?: string
}

export function ProcurementManagerSelector({ 
  selectedManager, 
  onManagerSelect, 
  disabled,
  placeholder = "조달담당자를 선택하세요",
  className
}: ProcurementManagerSelectorProps) {
  const [open, setOpen] = useState(false)
  const [managers, setManagers] = useState<ProcurementManager[]>([])
  const [sorting, setSorting] = useState<SortingState>([])
  const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([])
  const [columnVisibility, setColumnVisibility] = useState<VisibilityState>({})
  const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
  const [globalFilter, setGlobalFilter] = useState('')
  const [isPending, startTransition] = useTransition()

  // 조달담당자 선택 핸들러
  const handleManagerSelect = useCallback(async (manager: ProcurementManager) => {
    try {
      // 사용자 정보 추가
      const [managerWithUser] = await addUsersToManagersAsync(manager)
      onManagerSelect(managerWithUser)
      setOpen(false)
    } catch (error) {
      console.error('조달담당자 선택 오류:', error)
      toast.error('조달담당자 선택 중 오류가 발생했습니다.')
    }
  }, [onManagerSelect])

  // 테이블 컬럼 정의
  const columns: ColumnDef<ProcurementManager>[] = useMemo(() => [
    {
      accessorKey: 'PROCUREMENT_MANAGER_CODE',
      header: '조달담당자코드',
      cell: ({ row }) => (
        <div className="font-mono text-sm">{row.getValue('PROCUREMENT_MANAGER_CODE')}</div>
      ),
    },
    {
      accessorKey: 'DISPLAY_NAME',
      header: '담당자명',
      cell: ({ row }) => (
        <div>{row.getValue('DISPLAY_NAME')}</div>
      ),
    },
    {
      accessorKey: 'DEPARTMENT_NAME',
      header: '부서명',
      cell: ({ row }) => (
        <div className="text-sm text-muted-foreground">{row.getValue('DEPARTMENT_NAME')}</div>
      ),
    },
    {
      id: 'actions',
      header: '선택',
      cell: ({ row }) => (
        <Button
          variant="ghost"
          size="sm"
          onClick={(e) => {
            e.stopPropagation()
            handleManagerSelect(row.original)
          }}
        >
          <Check className="h-4 w-4" />
        </Button>
      ),
    },
  ], [handleManagerSelect])

  // 조달담당자 테이블 설정
  const table = useReactTable({
    data: managers,
    columns,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onColumnVisibilityChange: setColumnVisibility,
    onRowSelectionChange: setRowSelection,
    onGlobalFilterChange: setGlobalFilter,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    state: {
      sorting,
      columnFilters,
      columnVisibility,
      rowSelection,
      globalFilter,
    },
  })

  // 서버에서 조달담당자 전체 목록 로드 (한 번만)
  const loadManagers = useCallback(async () => {
    startTransition(async () => {
      try {
        const result = await getProcurementManagers()
        
        if (result.success) {
          setManagers(result.data)
        } else {
          toast.error(result.error || '조달담당자를 불러오는데 실패했습니다.')
          setManagers([])
        }
      } catch (error) {
        console.error('조달담당자 목록 로드 실패:', error)
        toast.error('조달담당자를 불러오는 중 오류가 발생했습니다.')
        setManagers([])
      }
    })
  }, [])

  // 다이얼로그 열기 핸들러
  const handleDialogOpenChange = useCallback((newOpen: boolean) => {
    setOpen(newOpen)
    if (newOpen && managers.length === 0) {
      loadManagers()
    }
  }, [loadManagers, managers.length])

  // 검색어 변경 핸들러 (클라이언트 사이드 필터링)
  const handleSearchChange = useCallback((value: string) => {
    setGlobalFilter(value)
  }, [])

  return (
    <Dialog open={open} onOpenChange={handleDialogOpenChange}>
      <DialogTrigger asChild>
        <Button 
          variant="outline" 
          disabled={disabled} 
          className={`w-full justify-start ${className || ''}`}
        >
          {selectedManager ? (
            <div className="flex items-center gap-2 w-full">
              <span className="font-mono text-sm">[{selectedManager.PROCUREMENT_MANAGER_CODE}]</span>
              <span className="truncate flex-1 text-left">{selectedManager.DISPLAY_NAME}</span>
              {selectedManager.DEPARTMENT_NAME && (
                <span className="text-xs text-muted-foreground">({selectedManager.DEPARTMENT_NAME})</span>
              )}
            </div>
          ) : (
            <span className="text-muted-foreground">{placeholder}</span>
          )}
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-5xl max-h-[80vh]">
        <DialogHeader>
          <DialogTitle>조달담당자 선택</DialogTitle>
          <div className="text-sm text-muted-foreground">
            조달담당자(CD_CLF=MMK010) 조회
          </div>
        </DialogHeader>
        
        <div className="space-y-4">
          <div className="flex items-center space-x-2">
            <Search className="h-4 w-4" />
            <Input
              placeholder="조달담당자코드, 담당자명, 부서명으로 검색..."
              value={globalFilter}
              onChange={(e) => handleSearchChange(e.target.value)}
              className="flex-1"
            />
          </div>

          {isPending ? (
            <div className="flex justify-center py-8">
              <div className="text-sm text-muted-foreground">조달담당자를 불러오는 중...</div>
            </div>
          ) : (
            <div className="border rounded-md">
              <Table>
                <TableHeader>
                  {table.getHeaderGroups().map((headerGroup) => (
                    <TableRow key={headerGroup.id}>
                      {headerGroup.headers.map((header) => (
                        <TableHead key={header.id}>
                          {header.isPlaceholder
                            ? null
                            : flexRender(
                                header.column.columnDef.header,
                                header.getContext()
                              )}
                        </TableHead>
                      ))}
                    </TableRow>
                  ))}
                </TableHeader>
                <TableBody>
                  {table.getRowModel().rows?.length ? (
                    table.getRowModel().rows.map((row) => (
                      <TableRow
                        key={row.id}
                        data-state={row.getIsSelected() && "selected"}
                        className="cursor-pointer hover:bg-muted/50"
                        onClick={() => handleManagerSelect(row.original)}
                      >
                        {row.getVisibleCells().map((cell) => (
                          <TableCell key={cell.id}>
                            {flexRender(
                              cell.column.columnDef.cell,
                              cell.getContext()
                            )}
                          </TableCell>
                        ))}
                      </TableRow>
                    ))
                  ) : (
                    <TableRow>
                      <TableCell
                        colSpan={columns.length}
                        className="h-24 text-center"
                      >
                        검색 결과가 없습니다.
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          )}

          <div className="flex items-center justify-between">
            <div className="text-sm text-muted-foreground">
              총 {table.getFilteredRowModel().rows.length}개 조달담당자
            </div>
            <div className="flex items-center space-x-2">
              <Button
                variant="outline"
                size="sm"
                onClick={() => table.previousPage()}
                disabled={!table.getCanPreviousPage()}
              >
                이전
              </Button>
              <div className="text-sm">
                {table.getState().pagination.pageIndex + 1} / {table.getPageCount()}
              </div>
              <Button
                variant="outline"
                size="sm"
                onClick={() => table.nextPage()}
                disabled={!table.getCanNextPage()}
              >
                다음
              </Button>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  )
}

