'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Users, Edit, Trash2, UserCheck, UserX, Clock, Calendar, Mail, Plus, Upload } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  IntegratedListTemplateV2,
  type TabOption,
  type TableColumn,
  type StatCard,
} from '@/components/templates/IntegratedListTemplateV2';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { FieldSettingsDialog } from './FieldSettingsDialog';
import { UserInviteDialog } from './UserInviteDialog';
import type {
  Employee,
  EmployeeStatus,
  FieldSettings,
} from './types';
import {
  EMPLOYEE_STATUS_LABELS,
  EMPLOYEE_STATUS_COLORS,
  DEFAULT_FIELD_SETTINGS,
  USER_ROLE_LABELS,
} from './types';

// 필터 옵션 타입
type FilterOption = 'all' | 'hasUserId' | 'noUserId' | 'active' | 'leave' | 'resigned';

// 정렬 옵션 타입
type SortOption = 'rank' | 'hireDateDesc' | 'hireDateAsc' | 'departmentAsc' | 'departmentDesc' | 'nameAsc' | 'nameDesc';

// 필터 옵션 레이블
const FILTER_OPTIONS: { value: FilterOption; label: string }[] = [
  { value: 'all', label: '전체' },
  { value: 'hasUserId', label: '사용자 아이디 보유' },
  { value: 'noUserId', label: '사용자 아이디 미보유' },
  { value: 'active', label: '재직' },
  { value: 'leave', label: '휴직' },
  { value: 'resigned', label: '퇴직' },
];

// 정렬 옵션 레이블
const SORT_OPTIONS: { value: SortOption; label: string }[] = [
  { value: 'rank', label: '직급순' },
  { value: 'hireDateDesc', label: '입사일 최신순' },
  { value: 'hireDateAsc', label: '입사일 등록순' },
  { value: 'departmentAsc', label: '부서 오름차순' },
  { value: 'departmentDesc', label: '부서 내림차순' },
  { value: 'nameAsc', label: '이름 오름차순' },
  { value: 'nameDesc', label: '이름 내림차순' },
];

/**
 * Mock 데이터 - 실제 API 연동 전 테스트용
 */
const mockEmployees: Employee[] = [
  {
    id: '1',
    name: '김철수',
    employeeCode: 'abc123',
    phone: '010-1234-1234',
    email: 'abc@company.com',
    status: 'active',
    hireDate: '2025-09-11',
    departmentPositions: [
      { id: '1', departmentId: 'd1', departmentName: '부서명', positionId: 'p1', positionName: '부서장팀장' }
    ],
    rank: '부장',
    userInfo: { userId: 'abc', role: 'manager', accountStatus: 'active' },
    createdAt: '2020-03-15T00:00:00Z',
    updatedAt: '2024-01-15T00:00:00Z',
  },
  {
    id: '2',
    name: '이영희',
    employeeCode: 'abc123',
    phone: '010-1234-1234',
    email: 'abc@company.com',
    status: 'leave',
    hireDate: '2025-09-11',
    departmentPositions: [
      { id: '2', departmentId: 'd2', departmentName: '부서명', positionId: 'p2', positionName: '팀장' }
    ],
    rank: '부장',
    userInfo: { userId: 'abc', role: 'manager', accountStatus: 'active' },
    createdAt: '2019-06-01T00:00:00Z',
    updatedAt: '2024-02-20T00:00:00Z',
  },
  {
    id: '3',
    name: '박민수',
    employeeCode: 'abc123',
    phone: '010-1234-1234',
    email: 'abc@company.com',
    status: 'resigned',
    hireDate: '2025-09-11',
    departmentPositions: [
      { id: '3', departmentId: 'd1', departmentName: '부서명', positionId: 'p2', positionName: '부서장팀장' }
    ],
    rank: '부장',
    createdAt: '2021-01-10T00:00:00Z',
    updatedAt: '2024-03-01T00:00:00Z',
  },
  {
    id: '4',
    name: '정수진',
    employeeCode: 'abc123',
    phone: '010-1234-1234',
    email: 'abc@company.com',
    status: 'active',
    hireDate: '2025-09-11',
    departmentPositions: [
      { id: '4', departmentId: 'd3', departmentName: '부서명', positionId: 'p3', positionName: '팀장' }
    ],
    rank: '부장',
    createdAt: '2018-09-20T00:00:00Z',
    updatedAt: '2024-01-30T00:00:00Z',
  },
];

// 추가 mock 데이터 생성 (55명 재직, 5명 휴직, 1명 퇴직)
// SSR Hydration 오류 방지: Math.random(), new Date() 대신 고정값 사용
const generateMockEmployees = (): Employee[] => {
  const employees: Employee[] = [...mockEmployees];
  const departments = ['부서명'];
  const positions = ['팀장', '부서장팀장', '파트장'];
  const ranks = ['부장'];

  for (let i = 5; i <= 61; i++) {
    const status: EmployeeStatus = i <= 55 ? 'active' : i <= 60 ? 'leave' : 'resigned';
    employees.push({
      id: String(i),
      name: `이름`,
      employeeCode: `abc123`,
      phone: `010-1234-1234`,
      email: `abc@company.com`,
      status,
      hireDate: `2025-09-11`,
      departmentPositions: [
        {
          id: String(i),
          departmentId: `d${(i % 5) + 1}`,
          departmentName: departments[0],
          positionId: `p${(i % 3) + 1}`,
          positionName: positions[i % positions.length],
        }
      ],
      rank: ranks[0],
      userInfo: i % 3 !== 0 ? {
        userId: `abc`,
        role: 'user',
        accountStatus: 'active',
      } : undefined,
      createdAt: '2025-01-01T00:00:00Z',
      updatedAt: '2025-01-01T00:00:00Z',
    });
  }
  return employees;
};

export function EmployeeManagement() {
  const router = useRouter();

  // 사원 데이터 상태
  const [employees, setEmployees] = useState<Employee[]>(generateMockEmployees);

  // 검색 및 필터 상태
  const [searchValue, setSearchValue] = useState('');
  const [activeTab, setActiveTab] = useState<string>('all');
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 날짜 범위 상태 (Input type="date" 용)
  const [startDate, setStartDate] = useState('2025-12-01');
  const [endDate, setEndDate] = useState('2025-12-31');

  // 필터 및 정렬 상태
  const [filterOption, setFilterOption] = useState<FilterOption>('all');
  const [sortOption, setSortOption] = useState<SortOption>('rank');

  // 다이얼로그 상태
  const [fieldSettingsOpen, setFieldSettingsOpen] = useState(false);
  const [fieldSettings, setFieldSettings] = useState<FieldSettings>(DEFAULT_FIELD_SETTINGS);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [employeeToDelete, setEmployeeToDelete] = useState<Employee | null>(null);
  const [userInviteOpen, setUserInviteOpen] = useState(false);
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());

  // 필터링된 데이터
  const filteredEmployees = useMemo(() => {
    let filtered = employees;

    // 탭 필터 (상태)
    if (activeTab !== 'all') {
      filtered = filtered.filter(e => e.status === activeTab);
    }

    // 셀렉트박스 필터
    if (filterOption !== 'all') {
      switch (filterOption) {
        case 'hasUserId':
          filtered = filtered.filter(e => e.userInfo?.userId);
          break;
        case 'noUserId':
          filtered = filtered.filter(e => !e.userInfo?.userId);
          break;
        case 'active':
          filtered = filtered.filter(e => e.status === 'active');
          break;
        case 'leave':
          filtered = filtered.filter(e => e.status === 'leave');
          break;
        case 'resigned':
          filtered = filtered.filter(e => e.status === 'resigned');
          break;
      }
    }

    // 검색 필터
    if (searchValue) {
      const search = searchValue.toLowerCase();
      filtered = filtered.filter(e =>
        e.name.toLowerCase().includes(search) ||
        e.employeeCode?.toLowerCase().includes(search) ||
        e.email?.toLowerCase().includes(search)
      );
    }

    // 정렬
    filtered = [...filtered].sort((a, b) => {
      switch (sortOption) {
        case 'rank':
          // 직급 순서 정의 (높은 직급이 먼저)
          const rankOrder: Record<string, number> = { '회장': 1, '사장': 2, '부사장': 3, '전무': 4, '상무': 5, '이사': 6, '부장': 7, '차장': 8, '과장': 9, '대리': 10, '주임': 11, '사원': 12 };
          return (rankOrder[a.rank || ''] || 99) - (rankOrder[b.rank || ''] || 99);
        case 'hireDateDesc':
          return new Date(b.hireDate || 0).getTime() - new Date(a.hireDate || 0).getTime();
        case 'hireDateAsc':
          return new Date(a.hireDate || 0).getTime() - new Date(b.hireDate || 0).getTime();
        case 'departmentAsc':
          const deptA = a.departmentPositions?.[0]?.departmentName || '';
          const deptB = b.departmentPositions?.[0]?.departmentName || '';
          return deptA.localeCompare(deptB, 'ko');
        case 'departmentDesc':
          const deptA2 = a.departmentPositions?.[0]?.departmentName || '';
          const deptB2 = b.departmentPositions?.[0]?.departmentName || '';
          return deptB2.localeCompare(deptA2, 'ko');
        case 'nameAsc':
          return a.name.localeCompare(b.name, 'ko');
        case 'nameDesc':
          return b.name.localeCompare(a.name, 'ko');
        default:
          return 0;
      }
    });

    return filtered;
  }, [employees, activeTab, filterOption, sortOption, searchValue]);

  // 페이지네이션된 데이터
  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredEmployees.slice(startIndex, startIndex + itemsPerPage);
  }, [filteredEmployees, currentPage, itemsPerPage]);

  // 통계 계산
  // SSR Hydration 오류 방지: new Date() 대신 고정 날짜 사용
  const stats = useMemo(() => {
    const activeCount = employees.filter(e => e.status === 'active').length;
    const leaveCount = employees.filter(e => e.status === 'leave').length;
    const resignedCount = employees.filter(e => e.status === 'resigned').length;

    const activeEmployees = employees.filter(e => e.status === 'active' && e.hireDate);
    // 고정 기준일 사용 (SSR/CSR 일치)
    const referenceDate = new Date('2025-12-16T00:00:00Z');
    const totalTenure = activeEmployees.reduce((sum, e) => {
      const hireDate = new Date(e.hireDate!);
      const years = (referenceDate.getTime() - hireDate.getTime()) / (1000 * 60 * 60 * 24 * 365);
      return sum + years;
    }, 0);
    const averageTenure = activeEmployees.length > 0 ? totalTenure / activeEmployees.length : 0;

    return { activeCount, leaveCount, resignedCount, averageTenure };
  }, [employees]);

  // StatCards 데이터
  const statCards: StatCard[] = useMemo(() => [
    {
      label: '재직',
      value: `${stats.activeCount}명`,
      icon: UserCheck,
      iconColor: 'text-green-500',
    },
    {
      label: '휴직',
      value: `${stats.leaveCount}명`,
      icon: Clock,
      iconColor: 'text-yellow-500',
    },
    {
      label: '퇴직',
      value: `${stats.resignedCount}명`,
      icon: UserX,
      iconColor: 'text-gray-500',
    },
    {
      label: '평균근속년수',
      value: `${stats.averageTenure.toFixed(1)}년`,
      icon: Calendar,
      iconColor: 'text-blue-500',
    },
  ], [stats]);

  // 탭 옵션
  const tabs: TabOption[] = useMemo(() => [
    { value: 'all', label: '전체', count: employees.length, color: 'gray' },
    { value: 'active', label: '재직', count: stats.activeCount, color: 'green' },
    { value: 'leave', label: '휴직', count: stats.leaveCount, color: 'yellow' },
    { value: 'resigned', label: '퇴직', count: stats.resignedCount, color: 'gray' },
  ], [employees.length, stats]);

  // 테이블 컬럼 정의
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'rowNumber', label: '번호', className: 'w-[60px] text-center' },
    { key: 'employeeCode', label: '사원코드', className: 'min-w-[100px]' },
    { key: 'department', label: '부서', className: 'min-w-[100px]' },
    { key: 'position', label: '직책', className: 'min-w-[100px]' },
    { key: 'name', label: '이름', className: 'min-w-[80px]' },
    { key: 'rank', label: '직급', className: 'min-w-[80px]' },
    { key: 'phone', label: '휴대폰', className: 'min-w-[120px]' },
    { key: 'email', label: '이메일', className: 'min-w-[150px]' },
    { key: 'hireDate', label: '입사일', className: 'min-w-[100px]' },
    { key: 'status', label: '상태', className: 'min-w-[80px]' },
    { key: 'userId', label: '사용자아이디', className: 'min-w-[100px]' },
    { key: 'userRole', label: '권한', className: 'min-w-[80px]' },
    { key: 'actions', label: '작업', className: 'w-[100px] text-right' },
  ], []);

  // 체크박스 토글
  const toggleSelection = useCallback((id: string) => {
    setSelectedItems(prev => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  }, []);

  // 전체 선택/해제
  const toggleSelectAll = useCallback(() => {
    if (selectedItems.size === paginatedData.length && paginatedData.length > 0) {
      setSelectedItems(new Set());
    } else {
      const allIds = new Set(paginatedData.map((item) => item.id));
      setSelectedItems(allIds);
    }
  }, [selectedItems.size, paginatedData]);

  // 일괄 삭제 핸들러
  const handleBulkDelete = useCallback(() => {
    const ids = Array.from(selectedItems);
    setEmployees(prev => prev.filter(emp => !ids.includes(emp.id)));
    setSelectedItems(new Set());
  }, [selectedItems]);

  // 핸들러
  const handleAddEmployee = useCallback(() => {
    router.push('/ko/hr/employee-management/new');
  }, [router]);

  const handleCSVUpload = useCallback(() => {
    router.push('/ko/hr/employee-management/csv-upload');
  }, [router]);

  const handleDeleteEmployee = useCallback(() => {
    if (employeeToDelete) {
      setEmployees(prev => prev.filter(emp => emp.id !== employeeToDelete.id));
      setDeleteDialogOpen(false);
      setEmployeeToDelete(null);
    }
  }, [employeeToDelete]);

  const handleRowClick = useCallback((row: Employee) => {
    router.push(`/ko/hr/employee-management/${row.id}`);
  }, [router]);

  const handleEdit = useCallback((id: string) => {
    router.push(`/ko/hr/employee-management/${id}/edit`);
  }, [router]);

  const openDeleteDialog = useCallback((employee: Employee) => {
    setEmployeeToDelete(employee);
    setDeleteDialogOpen(true);
  }, []);

  // 테이블 행 렌더링
  const renderTableRow = useCallback((item: Employee, index: number, globalIndex: number) => {
    const isSelected = selectedItems.has(item.id);

    return (
      <TableRow
        key={item.id}
        className="hover:bg-muted/50 cursor-pointer"
        onClick={() => handleRowClick(item)}
      >
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox
            checked={isSelected}
            onCheckedChange={() => toggleSelection(item.id)}
          />
        </TableCell>
        <TableCell className="text-muted-foreground text-center">
          {globalIndex}
        </TableCell>
        <TableCell>{item.employeeCode || '-'}</TableCell>
        <TableCell>
          {item.departmentPositions?.length > 0
            ? item.departmentPositions.map(dp => dp.departmentName).join(', ')
            : '-'}
        </TableCell>
        <TableCell>
          {item.departmentPositions?.length > 0
            ? item.departmentPositions.map(dp => dp.positionName).join(', ')
            : '-'}
        </TableCell>
        <TableCell>{item.name}</TableCell>
        <TableCell>{item.rank || '-'}</TableCell>
        <TableCell>{item.phone || '-'}</TableCell>
        <TableCell>{item.email || '-'}</TableCell>
        <TableCell>
          {item.hireDate ? new Date(item.hireDate).toLocaleDateString('ko-KR') : '-'}
        </TableCell>
        <TableCell>
          <Badge className={EMPLOYEE_STATUS_COLORS[item.status]}>
            {EMPLOYEE_STATUS_LABELS[item.status]}
          </Badge>
        </TableCell>
        <TableCell>{item.userInfo?.userId || '-'}</TableCell>
        <TableCell>
          {item.userInfo ? USER_ROLE_LABELS[item.userInfo.role] : '-'}
        </TableCell>
        <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
          {isSelected && (
            <div className="flex items-center justify-end gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => handleEdit(item.id)}
                title="수정"
              >
                <Edit className="w-4 h-4" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => openDeleteDialog(item)}
                title="삭제"
              >
                <Trash2 className="w-4 h-4 text-red-500" />
              </Button>
            </div>
          )}
        </TableCell>
      </TableRow>
    );
  }, [selectedItems, toggleSelection, handleRowClick, handleEdit, openDeleteDialog]);

  // 모바일 카드 렌더링
  const renderMobileCard = useCallback((
    item: Employee,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        id={item.id}
        title={item.name}
        headerBadges={
          <div className="flex items-center gap-2 flex-wrap">
            <Badge variant="outline" className="text-xs">
              #{globalIndex}
            </Badge>
            <code className="text-xs bg-gray-100 px-2 py-1 rounded">
              {item.employeeCode}
            </code>
          </div>
        }
        statusBadge={
          <Badge className={EMPLOYEE_STATUS_COLORS[item.status]}>
            {EMPLOYEE_STATUS_LABELS[item.status]}
          </Badge>
        }
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onCardClick={() => handleRowClick(item)}
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField
              label="부서"
              value={item.departmentPositions?.length > 0
                ? item.departmentPositions.map(dp => dp.departmentName).join(', ')
                : '-'}
            />
            <InfoField
              label="직책"
              value={item.departmentPositions?.length > 0
                ? item.departmentPositions.map(dp => dp.positionName).join(', ')
                : '-'}
            />
            <InfoField label="직급" value={item.rank || '-'} />
            <InfoField label="휴대폰" value={item.phone || '-'} />
            <InfoField label="이메일" value={item.email || '-'} />
            <InfoField
              label="입사일"
              value={item.hireDate ? new Date(item.hireDate).toLocaleDateString('ko-KR') : '-'}
            />
            {item.userInfo && (
              <>
                <InfoField label="사용자ID" value={item.userInfo.userId || '-'} />
                <InfoField label="권한" value={USER_ROLE_LABELS[item.userInfo.role]} />
              </>
            )}
          </div>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 flex-wrap">
              <Button
                variant="default"
                size="default"
                className="flex-1 min-w-[100px] h-11"
                onClick={(e) => { e.stopPropagation(); handleEdit(item.id); }}
              >
                <Edit className="h-4 w-4 mr-2" />
                수정
              </Button>
              <Button
                variant="outline"
                size="default"
                className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-transparent"
                onClick={(e) => { e.stopPropagation(); openDeleteDialog(item); }}
              >
                <Trash2 className="h-4 w-4 mr-2" />
                삭제
              </Button>
            </div>
          ) : undefined
        }
      />
    );
  }, [handleRowClick, handleEdit, openDeleteDialog]);

  // 헤더 액션 (DateRangeSelector + 버튼들)
  const headerActions = (
    <>
      <DateRangeSelector
        startDate={startDate}
        endDate={endDate}
        onStartDateChange={setStartDate}
        onEndDateChange={setEndDate}
      />
      <div className="ml-auto flex gap-2">
        <Button
          variant="outline"
          onClick={() => setUserInviteOpen(true)}
        >
          <Mail className="w-4 h-4 mr-2" />
          사용자 초대
        </Button>
        <Button variant="outline" onClick={handleCSVUpload}>
          <Upload className="w-4 h-4 mr-2" />
          CSV 일괄 등록
        </Button>
        <Button onClick={handleAddEmployee}>
          <Plus className="w-4 h-4 mr-2" />
          사원 등록
        </Button>
      </div>
    </>
  );

  // 테이블 헤더 액션 (필터/정렬 셀렉트박스)
  const tableHeaderActions = (
    <div className="flex items-center gap-2">
      {/* 필터 셀렉트박스 */}
      <Select value={filterOption} onValueChange={(value) => setFilterOption(value as FilterOption)}>
        <SelectTrigger className="w-[180px]">
          <SelectValue placeholder="필터 선택" />
        </SelectTrigger>
        <SelectContent>
          {FILTER_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* 정렬 셀렉트박스 */}
      <Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
        <SelectTrigger className="w-[150px]">
          <SelectValue placeholder="정렬 선택" />
        </SelectTrigger>
        <SelectContent>
          {SORT_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );

  // 페이지네이션 설정
  const totalPages = Math.ceil(filteredEmployees.length / itemsPerPage);

  return (
    <>
      <IntegratedListTemplateV2<Employee>
        title="사원관리"
        description="사원 정보를 관리합니다"
        icon={Users}
        headerActions={headerActions}
        stats={statCards}
        searchValue={searchValue}
        onSearchChange={setSearchValue}
        searchPlaceholder="이름, 사원코드, 이메일 검색..."
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        tableHeaderActions={tableHeaderActions}
        tableColumns={tableColumns}
        data={paginatedData}
        totalCount={filteredEmployees.length}
        allData={filteredEmployees}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        onBulkDelete={handleBulkDelete}
        getItemId={(item) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredEmployees.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
      />

      {/* 필드 설정 다이얼로그 */}
      <FieldSettingsDialog
        open={fieldSettingsOpen}
        onOpenChange={setFieldSettingsOpen}
        settings={fieldSettings}
        onSave={setFieldSettings}
      />

      {/* 사용자 초대 다이얼로그 */}
      <UserInviteDialog
        open={userInviteOpen}
        onOpenChange={setUserInviteOpen}
        onInvite={(data) => {
          console.log('Invite user:', data);
          setUserInviteOpen(false);
        }}
      />

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>사원 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              &quot;{employeeToDelete?.name}&quot; 사원을 삭제하시겠습니까?
              <br />
              <span className="text-destructive">
                삭제된 사원 정보는 복구할 수 없습니다.
              </span>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDeleteEmployee}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}