'use client';

import { useState, useMemo, useCallback } from 'react';
import { format } from 'date-fns';
import {
  Download,
  Plus,
  Calendar,
  Check,
  X,
  Clock,
  Heart,
  TrendingUp,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
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 TableColumn,
  type StatCard,
  type TabOption,
} from '@/components/templates/IntegratedListTemplateV2';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { VacationGrantDialog } from './VacationGrantDialog';
import { VacationRequestDialog } from './VacationRequestDialog';
import type {
  MainTabType,
  VacationUsageRecord,
  VacationGrantRecord,
  VacationRequestRecord,
  SortOption,
  FilterOption,
  VacationType,
  RequestStatus,
} from './types';
import {
  MAIN_TAB_LABELS,
  SORT_OPTIONS,
  FILTER_OPTIONS,
  VACATION_TYPE_LABELS,
  REQUEST_STATUS_LABELS,
  REQUEST_STATUS_COLORS,
} from './types';

// ===== Mock 데이터 생성 =====
const generateUsageData = (): VacationUsageRecord[] => {
  const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
  const positions = ['팀장', '파트장', '선임', '주임', '사원'];
  const ranks = ['부장', '차장', '과장', '대리', '사원'];

  // 휴가 일수 포맷: "15일", "12일3시간" 등
  const usedVacations = ['12일3시간', '8일', '5일4시간', '10일', '3일2시간', '7일5시간', '9일', '6일1시간', '4일', '11일6시간'];
  const remainingVacations = ['2일5시간', '7일', '9일4시간', '5일', '11일6시간', '7일3시간', '6일', '8일7시간', '11일', '3일2시간'];
  const grantedVacations = ['0일', '3일', '2일', '1일', '4일', '0일', '2일', '3일', '1일', '0일'];

  return Array.from({ length: 10 }, (_, i) => ({
    id: `usage-${i + 1}`,
    employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
    employeeName: ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호', '임지현', '한승우', '송예진'][i],
    department: departments[i % departments.length],
    position: positions[i % positions.length],
    rank: ranks[i % ranks.length],
    hireDate: format(new Date(2020 + (i % 5), i % 12, (i % 28) + 1), 'yyyy-MM-dd'),
    baseVacation: '15일',
    grantedVacation: grantedVacations[i],
    usedVacation: usedVacations[i],
    remainingVacation: remainingVacations[i],
    // 휴가 유형별 상세 (조정 다이얼로그용)
    annual: { total: 15, used: 10 + (i % 5), remaining: 5 - (i % 5) },
    monthly: { total: 3, used: i % 3, remaining: 3 - (i % 3) },
    reward: { total: i % 4, used: 0, remaining: i % 4 },
    other: { total: 0, used: 0, remaining: 0 },
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  }));
};

const generateGrantData = (): VacationGrantRecord[] => {
  const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
  const positions = ['팀장', '파트장', '선임', '주임', '사원'];
  const ranks = ['부장', '차장', '과장', '대리', '사원'];
  const vacationTypes: VacationType[] = ['annual', 'monthly', 'reward', 'condolence', 'other'];
  const reasons = ['연차 부여', '월차 부여', '포상 휴가', '경조사 휴가', '기타 휴가'];

  return Array.from({ length: 10 }, (_, i) => ({
    id: `grant-${i + 1}`,
    employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
    employeeName: ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호', '임지현', '한승우', '송예진'][i],
    department: departments[i % departments.length],
    position: positions[i % positions.length],
    rank: ranks[i % ranks.length],
    vacationType: vacationTypes[i % vacationTypes.length],
    grantDate: format(new Date(2025, 11, (i % 28) + 1), 'yyyy-MM-dd'),
    grantDays: Math.floor(Math.random() * 5) + 1,
    reason: reasons[i % reasons.length],
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
  }));
};

const generateRequestData = (): VacationRequestRecord[] => {
  const departments = ['개발팀', '디자인팀', '기획팀', '영업팀', '인사팀'];
  const positions = ['팀장', '파트장', '선임', '주임', '사원'];
  const ranks = ['부장', '차장', '과장', '대리', '사원'];
  const statuses: RequestStatus[] = ['pending', 'approved', 'rejected'];

  return Array.from({ length: 7 }, (_, i) => {
    const startDate = new Date(2025, 11, (i % 28) + 1);
    const endDate = new Date(startDate);
    endDate.setDate(endDate.getDate() + Math.floor(Math.random() * 5) + 1);

    return {
      id: `request-${i + 1}`,
      employeeId: `EMP${String(i + 1).padStart(3, '0')}`,
      employeeName: ['김철수', '이영희', '박민수', '정수진', '최동현', '강미영', '윤상호'][i],
      department: departments[i % departments.length],
      position: positions[i % positions.length],
      rank: ranks[i % ranks.length],
      startDate: format(startDate, 'yyyy-MM-dd'),
      endDate: format(endDate, 'yyyy-MM-dd'),
      vacationDays: Math.floor(Math.random() * 5) + 1,
      status: statuses[i % statuses.length],
      requestDate: format(new Date(2025, 11, i + 1), 'yyyy-MM-dd'),
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
  });
};

export function VacationManagement() {
  // ===== 상태 관리 =====
  const [mainTab, setMainTab] = useState<MainTabType>('usage');
  const [searchQuery, setSearchQuery] = useState('');
  const [filterOption, setFilterOption] = useState<FilterOption>('all');
  const [sortOption, setSortOption] = useState<SortOption>('rank');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  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 [grantDialogOpen, setGrantDialogOpen] = useState(false);
  const [requestDialogOpen, setRequestDialogOpen] = useState(false);
  const [approveDialogOpen, setApproveDialogOpen] = useState(false);
  const [rejectDialogOpen, setRejectDialogOpen] = useState(false);

  // Mock 데이터
  const [usageData] = useState<VacationUsageRecord[]>(generateUsageData);
  const [grantData] = useState<VacationGrantRecord[]>(generateGrantData);
  const [requestData] = useState<VacationRequestRecord[]>(generateRequestData);

  // ===== 탭 변경 핸들러 =====
  const handleMainTabChange = useCallback((value: string) => {
    setMainTab(value as MainTabType);
    setSelectedItems(new Set());
    setSearchQuery('');
    setCurrentPage(1);
  }, []);

  // ===== 체크박스 핸들러 =====
  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(() => {
    const currentData = mainTab === 'usage' ? filteredUsageData : mainTab === 'grant' ? filteredGrantData : filteredRequestData;
    if (selectedItems.size === currentData.length && currentData.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(currentData.map(item => item.id)));
    }
  }, [mainTab, selectedItems.size]);

  // ===== 필터링된 데이터 =====
  const filteredUsageData = useMemo(() => {
    return usageData.filter(item =>
      item.employeeName.includes(searchQuery) ||
      item.department.includes(searchQuery)
    );
  }, [usageData, searchQuery]);

  const filteredGrantData = useMemo(() => {
    return grantData.filter(item =>
      item.employeeName.includes(searchQuery) ||
      item.department.includes(searchQuery)
    );
  }, [grantData, searchQuery]);

  const filteredRequestData = useMemo(() => {
    return requestData.filter(item =>
      item.employeeName.includes(searchQuery) ||
      item.department.includes(searchQuery)
    );
  }, [requestData, searchQuery]);

  // ===== 현재 탭 데이터 =====
  const currentData = useMemo(() => {
    switch (mainTab) {
      case 'usage': return filteredUsageData;
      case 'grant': return filteredGrantData;
      case 'request': return filteredRequestData;
      default: return [];
    }
  }, [mainTab, filteredUsageData, filteredGrantData, filteredRequestData]);

  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return currentData.slice(startIndex, startIndex + itemsPerPage);
  }, [currentData, currentPage, itemsPerPage]);

  const totalPages = Math.ceil(currentData.length / itemsPerPage);

  // ===== 승인/거절 핸들러 =====
  const handleApproveClick = useCallback(() => {
    if (selectedItems.size === 0) return;
    setApproveDialogOpen(true);
  }, [selectedItems.size]);

  const handleApproveConfirm = useCallback(() => {
    console.log('승인:', Array.from(selectedItems));
    // TODO: API 호출
    setSelectedItems(new Set());
    setApproveDialogOpen(false);
    // 완료 알림은 toast로 대체하거나 간단히 처리
  }, [selectedItems]);

  const handleRejectClick = useCallback(() => {
    if (selectedItems.size === 0) return;
    setRejectDialogOpen(true);
  }, [selectedItems.size]);

  const handleRejectConfirm = useCallback(() => {
    console.log('거절:', Array.from(selectedItems));
    // TODO: API 호출
    setSelectedItems(new Set());
    setRejectDialogOpen(false);
    // 완료 알림은 toast로 대체하거나 간단히 처리
  }, [selectedItems]);

  // ===== 통계 카드 (기획서: 휴가 승인 대기, 연차, 경조사, 연간 연차 사용률) =====
  const statCards: StatCard[] = useMemo(() => {
    // 휴가 승인 대기 (pending 상태인 request 수)
    const pendingCount = requestData.filter(r => r.status === 'pending').length;

    // 연차 사용자 수
    const annualCount = usageData.length;

    // 경조사 휴가 수
    const condolenceCount = grantData.filter(g => g.vacationType === 'condolence').length;

    // 연간 연차 사용률 계산 (총 사용일 / 총 부여일 * 100)
    const totalUsed = usageData.reduce((sum, u) => sum + u.annual.used, 0);
    const totalAvailable = usageData.reduce((sum, u) => sum + u.annual.total, 0);
    const usageRate = totalAvailable > 0 ? ((totalUsed / totalAvailable) * 100).toFixed(1) : '0.0';

    return [
      { label: '휴가 승인 대기', value: `${pendingCount}명`, icon: Clock, iconColor: 'text-yellow-500' },
      { label: '연차', value: `${annualCount}명`, icon: Calendar, iconColor: 'text-blue-500' },
      { label: '경조사', value: `${condolenceCount}명`, icon: Heart, iconColor: 'text-pink-500' },
      { label: '연간 연차 사용률', value: `${usageRate}%`, icon: TrendingUp, iconColor: 'text-green-500' },
    ];
  }, [usageData, grantData, requestData]);

  // ===== 탭 옵션 (카드 아래에 표시됨) =====
  const tabs: TabOption[] = useMemo(() => [
    { value: 'usage', label: MAIN_TAB_LABELS.usage, count: usageData.length, color: 'blue' },
    { value: 'grant', label: MAIN_TAB_LABELS.grant, count: grantData.length, color: 'green' },
    { value: 'request', label: MAIN_TAB_LABELS.request, count: requestData.length, color: 'purple' },
  ], [usageData.length, grantData.length, requestData.length]);

  // ===== 테이블 컬럼 (탭별) =====
  const tableColumns: TableColumn[] = useMemo(() => {
    if (mainTab === 'usage') {
      // 휴가 사용현황: 번호|부서|직책|이름|직급|입사일|기본|부여|사용|잔액
      return [
        { key: 'no', label: '번호', className: 'w-[60px] text-center' },
        { key: 'department', label: '부서' },
        { key: 'position', label: '직책' },
        { key: 'name', label: '이름' },
        { key: 'rank', label: '직급' },
        { key: 'hireDate', label: '입사일' },
        { key: 'base', label: '기본', className: 'text-center' },
        { key: 'granted', label: '부여', className: 'text-center' },
        { key: 'used', label: '사용', className: 'text-center' },
        { key: 'remaining', label: '잔여', className: 'text-center' },
      ];
    } else if (mainTab === 'grant') {
      // 휴가 부여현황: 번호|부서|직책|이름|직급|유형|부여일|부여휴가일수|사유
      return [
        { key: 'no', label: '번호', className: 'w-[60px] text-center' },
        { key: 'department', label: '부서' },
        { key: 'position', label: '직책' },
        { key: 'name', label: '이름' },
        { key: 'rank', label: '직급' },
        { key: 'type', label: '유형' },
        { key: 'grantDate', label: '부여일' },
        { key: 'grantDays', label: '부여휴가일수', className: 'text-center' },
        { key: 'reason', label: '사유' },
      ];
    } else {
      // 휴가 신청현황: 번호|부서|직책|이름|직급|휴가기간|휴가일수|상태|신청일
      return [
        { key: 'no', label: '번호', className: 'w-[60px] text-center' },
        { key: 'department', label: '부서' },
        { key: 'position', label: '직책' },
        { key: 'name', label: '이름' },
        { key: 'rank', label: '직급' },
        { key: 'period', label: '휴가기간' },
        { key: 'days', label: '휴가일수', className: 'text-center' },
        { key: 'status', label: '상태', className: 'text-center' },
        { key: 'requestDate', label: '신청일' },
      ];
    }
  }, [mainTab]);

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

    if (mainTab === 'usage') {
      const record = item as VacationUsageRecord;
      return (
        <TableRow key={record.id} className="hover:bg-muted/50">
          <TableCell className="text-center">
            <Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
          </TableCell>
          <TableCell className="text-center">{globalIndex}</TableCell>
          <TableCell>{record.department}</TableCell>
          <TableCell>{record.position}</TableCell>
          <TableCell className="font-medium">{record.employeeName}</TableCell>
          <TableCell>{record.rank}</TableCell>
          <TableCell>{format(new Date(record.hireDate), 'yyyy-MM-dd')}</TableCell>
          <TableCell className="text-center">{record.baseVacation}</TableCell>
          <TableCell className="text-center">{record.grantedVacation}</TableCell>
          <TableCell className="text-center">{record.usedVacation}</TableCell>
          <TableCell className="text-center font-medium">{record.remainingVacation}</TableCell>
        </TableRow>
      );
    } else if (mainTab === 'grant') {
      const record = item as VacationGrantRecord;
      return (
        <TableRow key={record.id} className="hover:bg-muted/50">
          <TableCell className="text-center">
            <Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
          </TableCell>
          <TableCell className="text-center">{globalIndex}</TableCell>
          <TableCell>{record.department}</TableCell>
          <TableCell>{record.position}</TableCell>
          <TableCell className="font-medium">{record.employeeName}</TableCell>
          <TableCell>{record.rank}</TableCell>
          <TableCell>
            <Badge variant="outline">{VACATION_TYPE_LABELS[record.vacationType]}</Badge>
          </TableCell>
          <TableCell>{format(new Date(record.grantDate), 'yyyy-MM-dd')}</TableCell>
          <TableCell className="text-center">{record.grantDays}일</TableCell>
          <TableCell className="text-muted-foreground">{record.reason || '-'}</TableCell>
        </TableRow>
      );
    } else {
      const record = item as VacationRequestRecord;
      return (
        <TableRow key={record.id} className="hover:bg-muted/50">
          <TableCell className="text-center">
            <Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(record.id)} />
          </TableCell>
          <TableCell className="text-center">{globalIndex}</TableCell>
          <TableCell>{record.department}</TableCell>
          <TableCell>{record.position}</TableCell>
          <TableCell className="font-medium">{record.employeeName}</TableCell>
          <TableCell>{record.rank}</TableCell>
          <TableCell>
            {format(new Date(record.startDate), 'yyyy-MM-dd')} ~ {format(new Date(record.endDate), 'yyyy-MM-dd')}
          </TableCell>
          <TableCell className="text-center">{record.vacationDays}일</TableCell>
          <TableCell className="text-center">
            <Badge className={REQUEST_STATUS_COLORS[record.status]}>
              {REQUEST_STATUS_LABELS[record.status]}
            </Badge>
          </TableCell>
          <TableCell>{format(new Date(record.requestDate), 'yyyy-MM-dd')}</TableCell>
        </TableRow>
      );
    }
  }, [mainTab, selectedItems, toggleSelection]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: any,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    if (mainTab === 'usage') {
      const record = item as VacationUsageRecord;
      return (
        <ListMobileCard
          id={record.id}
          title={record.employeeName}
          headerBadges={<Badge variant="outline">{record.department}</Badge>}
          isSelected={isSelected}
          onToggleSelection={onToggle}
          infoGrid={
            <div className="grid grid-cols-2 gap-3">
              <InfoField label="직급" value={record.rank} />
              <InfoField label="입사일" value={record.hireDate} />
              <InfoField label="기본" value={record.baseVacation} />
              <InfoField label="부여" value={record.grantedVacation} />
              <InfoField label="사용" value={record.usedVacation} />
              <InfoField label="잔여" value={record.remainingVacation} />
            </div>
          }
        />
      );
    } else if (mainTab === 'grant') {
      const record = item as VacationGrantRecord;
      return (
        <ListMobileCard
          id={record.id}
          title={record.employeeName}
          headerBadges={<Badge variant="outline">{VACATION_TYPE_LABELS[record.vacationType]}</Badge>}
          isSelected={isSelected}
          onToggleSelection={onToggle}
          infoGrid={
            <div className="grid grid-cols-2 gap-3">
              <InfoField label="부서" value={record.department} />
              <InfoField label="직급" value={record.rank} />
              <InfoField label="부여일" value={record.grantDate} />
              <InfoField label="일수" value={`${record.grantDays}일`} />
              {record.reason && <InfoField label="사유" value={record.reason} />}
            </div>
          }
        />
      );
    } else {
      const record = item as VacationRequestRecord;
      return (
        <ListMobileCard
          id={record.id}
          title={record.employeeName}
          headerBadges={
            <Badge className={REQUEST_STATUS_COLORS[record.status]}>
              {REQUEST_STATUS_LABELS[record.status]}
            </Badge>
          }
          isSelected={isSelected}
          onToggleSelection={onToggle}
          infoGrid={
            <div className="grid grid-cols-2 gap-3">
              <InfoField label="부서" value={record.department} />
              <InfoField label="직급" value={record.rank} />
              <InfoField label="기간" value={`${record.startDate} ~ ${record.endDate}`} />
              <InfoField label="일수" value={`${record.vacationDays}일`} />
              <InfoField label="신청일" value={record.requestDate} />
            </div>
          }
          actions={
            record.status === 'pending' && (
              <div className="flex gap-2">
                <Button variant="default" className="flex-1" onClick={handleApproveClick}>
                  <Check className="w-4 h-4 mr-2" /> 승인
                </Button>
                <Button variant="outline" className="flex-1" onClick={handleRejectClick}>
                  <X className="w-4 h-4 mr-2" /> 거절
                </Button>
              </div>
            )
          }
        />
      );
    }
  }, [mainTab, handleApproveClick, handleRejectClick]);

  // ===== 헤더 액션 (DateRangeSelector + 버튼들) =====
  const headerActions = (
    <>
      <DateRangeSelector
        startDate={startDate}
        endDate={endDate}
        onStartDateChange={setStartDate}
        onEndDateChange={setEndDate}
      />
      <div className="ml-auto flex gap-2">
        {/* 탭별 액션 버튼 */}
        {mainTab === 'grant' && (
          <Button onClick={() => setGrantDialogOpen(true)}>
            <Plus className="h-4 w-4 mr-2" />
            부여등록
          </Button>
        )}

        {mainTab === 'request' && (
          <>
            {/* 버튼 순서: 승인 → 거절 → 휴가신청 (휴가신청 버튼 위치 고정) */}
            {selectedItems.size > 0 && (
              <>
                <Button variant="default" onClick={handleApproveClick}>
                  <Check className="h-4 w-4 mr-2" />
                  승인
                </Button>
                <Button variant="destructive" onClick={handleRejectClick}>
                  <X className="h-4 w-4 mr-2" />
                  거절
                </Button>
              </>
            )}
            <Button onClick={() => setRequestDialogOpen(true)}>
              <Plus className="h-4 w-4 mr-2" />
              휴가신청
            </Button>
          </>
        )}

        {/* 엑셀 다운로드 버튼 - 주석처리 */}
        {/* <Button variant="outline" onClick={() => console.log('엑셀 다운로드')}>
          <Download className="h-4 w-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-[140px]">
          <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-[140px]">
          <SelectValue placeholder="정렬 선택" />
        </SelectTrigger>
        <SelectContent>
          {SORT_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );

  return (
    <>
      {/* IntegratedListTemplateV2 - 카드 아래에 탭 표시됨 */}
      <IntegratedListTemplateV2
        title="휴가관리"
        description="직원들의 휴가 현황을 관리합니다"
        icon={Calendar}
        headerActions={headerActions}
        stats={statCards}
        searchValue={searchQuery}
        onSearchChange={setSearchQuery}
        searchPlaceholder="이름, 부서 검색..."
        tableHeaderActions={tableHeaderActions}
        tabs={tabs}
        activeTab={mainTab}
        onTabChange={handleMainTabChange}
        tableColumns={tableColumns}
        data={paginatedData}
        totalCount={currentData.length}
        allData={currentData}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item: any) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: currentData.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
      />

      {/* 다이얼로그 */}
      <VacationGrantDialog
        open={grantDialogOpen}
        onOpenChange={setGrantDialogOpen}
        onSave={(data) => {
          console.log('부여 등록:', data);
          setGrantDialogOpen(false);
        }}
      />

      <VacationRequestDialog
        open={requestDialogOpen}
        onOpenChange={setRequestDialogOpen}
        onSave={(data) => {
          console.log('휴가 신청:', data);
          setRequestDialogOpen(false);
        }}
      />

      {/* 승인 확인 다이얼로그 */}
      <AlertDialog open={approveDialogOpen} onOpenChange={setApproveDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>휴가 승인</AlertDialogTitle>
            <AlertDialogDescription>
              정말 {selectedItems.size}건을 승인하시겠습니까?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={handleApproveConfirm}>
              승인
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* 거절 확인 다이얼로그 */}
      <AlertDialog open={rejectDialogOpen} onOpenChange={setRejectDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>휴가 거절</AlertDialogTitle>
            <AlertDialogDescription>
              정말 {selectedItems.size}건을 거절하시겠습니까?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleRejectConfirm}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              거절
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}