'use client';

import { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import { useDateRange } from '@/hooks';
import {
  DollarSign,
  Check,
  Clock,
  Banknote,
  Briefcase,
  Timer,
  Gift,
  MinusCircle,
  Loader2,
  Search,
  Plus,
} from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  UniversalListPage,
  type UniversalListConfig,
  type StatCard,
  type FilterFieldConfig,
  type FilterValues,
} from '@/components/templates/UniversalListPage';
import { usePermission } from '@/hooks/usePermission';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { SalaryDetailDialog } from './SalaryDetailDialog';
import { SalaryRegistrationDialog } from './SalaryRegistrationDialog';
import {
  getSalaries,
  getSalary,
  createSalary,
  bulkUpdateSalaryStatus,
  updateSalaryStatus,
  updateSalary,
} from './actions';
import type {
  SalaryRecord,
  SalaryDetail,
  PaymentStatus,
  SortOption,
} from './types';
import {
  PAYMENT_STATUS_LABELS,
  PAYMENT_STATUS_COLORS,
  SORT_OPTIONS,
  formatCurrency,
} from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

// ===== 목 데이터 (API 연동 전 테스트용) =====
const MOCK_SALARY_RECORDS: SalaryRecord[] = [
  {
    id: 'mock-1',
    employeeId: 'EMP001',
    employeeName: '김철수',
    department: '개발팀',
    position: '팀장',
    rank: '과장',
    baseSalary: 3500000,
    allowance: 850000,
    overtime: 320000,
    bonus: 0,
    deduction: 542000,
    netPayment: 4128000,
    paymentDate: '2026-02-25',
    status: 'scheduled',
    year: 2026,
    month: 2,
    createdAt: '2026-02-01',
    updatedAt: '2026-02-01',
  },
  {
    id: 'mock-2',
    employeeId: 'EMP002',
    employeeName: '이영희',
    department: '경영지원팀',
    position: '사원',
    rank: '대리',
    baseSalary: 3000000,
    allowance: 550000,
    overtime: 0,
    bonus: 500000,
    deduction: 468000,
    netPayment: 3582000,
    paymentDate: '2026-02-25',
    status: 'completed',
    year: 2026,
    month: 2,
    createdAt: '2026-02-01',
    updatedAt: '2026-02-20',
  },
];

const MOCK_SALARY_DETAILS: Record<string, SalaryDetail> = {
  'mock-1': {
    employeeId: 'EMP001',
    employeeName: '김철수',
    department: '개발팀',
    position: '팀장',
    rank: '과장',
    baseSalary: 3500000,
    allowances: {
      positionAllowance: 300000,
      overtimeAllowance: 320000,
      mealAllowance: 150000,
      transportAllowance: 100000,
      otherAllowance: 0,
    },
    deductions: {
      nationalPension: 157500,
      healthInsurance: 121450,
      longTermCare: 14820,
      employmentInsurance: 31500,
      incomeTax: 185230,
      localIncomeTax: 18520,
      otherDeduction: 12980,
    },
    totalAllowance: 870000,
    totalDeduction: 542000,
    netPayment: 4128000,
    paymentDate: '2026-02-25',
    status: 'scheduled',
    year: 2026,
    month: 2,
  },
  'mock-2': {
    employeeId: 'EMP002',
    employeeName: '이영희',
    department: '경영지원팀',
    position: '사원',
    rank: '대리',
    baseSalary: 3000000,
    allowances: {
      positionAllowance: 200000,
      overtimeAllowance: 0,
      mealAllowance: 150000,
      transportAllowance: 100000,
      otherAllowance: 100000,
    },
    deductions: {
      nationalPension: 135000,
      healthInsurance: 104100,
      longTermCare: 12700,
      employmentInsurance: 27000,
      incomeTax: 160200,
      localIncomeTax: 16020,
      otherDeduction: 12980,
    },
    totalAllowance: 550000,
    totalDeduction: 468000,
    netPayment: 3582000,
    paymentDate: '2026-02-25',
    status: 'completed',
    year: 2026,
    month: 2,
  },
};

export function SalaryManagement() {
  const { canExport } = usePermission();
  // ===== 상태 관리 =====
  const [searchQuery, setSearchQuery] = useState('');
  const [sortOption, setSortOption] = useState<SortOption>('rank');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 날짜 범위 상태
  const { startDate, endDate, setStartDate, setEndDate } = useDateRange('currentMonth');

  // 다이얼로그 상태
  const [detailDialogOpen, setDetailDialogOpen] = useState(false);
  const [selectedSalaryDetail, setSelectedSalaryDetail] = useState<SalaryDetail | null>(null);
  const [selectedSalaryId, setSelectedSalaryId] = useState<string | null>(null);
  const [registrationDialogOpen, setRegistrationDialogOpen] = useState(false);

  // 데이터 상태
  const [salaryData, setSalaryData] = useState<SalaryRecord[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const isInitialLoadDone = useRef(false);
  const [isActionLoading, setIsActionLoading] = useState(false);
  const [totalCount, setTotalCount] = useState(0);
  const [totalPages, setTotalPages] = useState(1);

  // ===== 데이터 로드 =====
  const loadSalaries = useCallback(async () => {
    if (!isInitialLoadDone.current) {
      setIsLoading(true);
    }
    try {
      const result = await getSalaries({
        search: searchQuery || undefined,
        start_date: startDate || undefined,
        end_date: endDate || undefined,
        page: currentPage,
        per_page: itemsPerPage,
      });

      if (result.success && result.data && result.data.length > 0) {
        setSalaryData(result.data);
        setTotalCount(result.pagination?.total || result.data.length);
        setTotalPages(result.pagination?.lastPage || 1);
      } else {
        // API 데이터가 없으면 목 데이터 사용
        setSalaryData(MOCK_SALARY_RECORDS);
        setTotalCount(MOCK_SALARY_RECORDS.length);
        setTotalPages(1);
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('loadSalaries error:', error);
      // API 실패 시에도 목 데이터 사용
      setSalaryData(MOCK_SALARY_RECORDS);
      setTotalCount(MOCK_SALARY_RECORDS.length);
      setTotalPages(1);
    } finally {
      setIsLoading(false);
      isInitialLoadDone.current = true;
    }
  }, [searchQuery, startDate, endDate, currentPage, itemsPerPage]);

  // 초기 데이터 로드 및 검색/필터 변경 시 재로드
  useEffect(() => {
    loadSalaries();
  }, [loadSalaries]);

  // ===== 체크박스 핸들러 =====
  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 === salaryData.length && salaryData.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(salaryData.map(item => item.id)));
    }
  }, [selectedItems.size, salaryData]);

  // ===== 지급완료 핸들러 =====
  const handleMarkCompleted = useCallback(async () => {
    if (selectedItems.size === 0) return;

    setIsActionLoading(true);
    try {
      const result = await bulkUpdateSalaryStatus(
        Array.from(selectedItems),
        'completed'
      );

      if (result.success) {
        toast.success(`${result.updatedCount || selectedItems.size}건이 지급완료 처리되었습니다.`);
        setSelectedItems(new Set());
        await loadSalaries();
      } else {
        toast.error(result.error || '상태 변경에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('handleMarkCompleted error:', error);
      toast.error('상태 변경에 실패했습니다.');
    } finally {
      setIsActionLoading(false);
    }
  }, [selectedItems, loadSalaries]);

  // ===== 지급예정 핸들러 =====
  const handleMarkScheduled = useCallback(async () => {
    if (selectedItems.size === 0) return;

    setIsActionLoading(true);
    try {
      const result = await bulkUpdateSalaryStatus(
        Array.from(selectedItems),
        'scheduled'
      );

      if (result.success) {
        toast.success(`${result.updatedCount || selectedItems.size}건이 지급예정 처리되었습니다.`);
        setSelectedItems(new Set());
        await loadSalaries();
      } else {
        toast.error(result.error || '상태 변경에 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('handleMarkScheduled error:', error);
      toast.error('상태 변경에 실패했습니다.');
    } finally {
      setIsActionLoading(false);
    }
  }, [selectedItems, loadSalaries]);

  // ===== 상세보기 핸들러 =====
  const handleViewDetail = useCallback(async (record: SalaryRecord) => {
    setSelectedSalaryId(record.id);
    setIsActionLoading(true);
    try {
      // 목 데이터인 경우 목 상세 데이터 사용
      if (record.id.startsWith('mock-')) {
        const mockDetail = MOCK_SALARY_DETAILS[record.id];
        if (mockDetail) {
          setSelectedSalaryDetail(mockDetail);
          setDetailDialogOpen(true);
        }
        return;
      }

      const result = await getSalary(record.id);
      if (result.success && result.data) {
        setSelectedSalaryDetail(result.data);
        setDetailDialogOpen(true);
      } else {
        toast.error(result.error || '급여 상세 정보를 불러오는데 실패했습니다.');
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('handleViewDetail error:', error);
      toast.error('급여 상세 정보를 불러오는데 실패했습니다.');
    } finally {
      setIsActionLoading(false);
    }
  }, []);

  // ===== 급여 상세 저장 핸들러 =====
  const handleSaveDetail = useCallback(async (
    updatedDetail: SalaryDetail,
    allowanceDetails?: Record<string, number>,
    deductionDetails?: Record<string, number>
  ) => {
    if (!selectedSalaryId) return;

    setIsActionLoading(true);
    try {
      // 목 데이터인 경우 로컬 상태만 업데이트
      if (selectedSalaryId.startsWith('mock-')) {
        setSalaryData(prev => prev.map(item =>
          item.id === selectedSalaryId
            ? {
                ...item,
                status: updatedDetail.status,
                allowance: updatedDetail.totalAllowance,
                deduction: updatedDetail.totalDeduction,
                netPayment: updatedDetail.netPayment,
              }
            : item
        ));
        toast.success('급여 정보가 저장되었습니다. (목 데이터)');
        setDetailDialogOpen(false);
        return;
      }

      // 수당/공제 정보가 변경된 경우 updateSalary API 호출
      if (allowanceDetails || deductionDetails) {
        const result = await updateSalary(selectedSalaryId, {
          allowance_details: allowanceDetails,
          deduction_details: deductionDetails,
          status: updatedDetail.status,
        });
        if (result.success) {
          toast.success('급여 정보가 저장되었습니다.');
          setDetailDialogOpen(false);
          await loadSalaries();
        } else {
          toast.error(result.error || '저장에 실패했습니다.');
        }
      } else {
        // 상태만 변경된 경우 기존 API 호출
        const result = await updateSalaryStatus(selectedSalaryId, updatedDetail.status);
        if (result.success) {
          toast.success('급여 정보가 저장되었습니다.');
          setDetailDialogOpen(false);
          await loadSalaries();
        } else {
          toast.error(result.error || '저장에 실패했습니다.');
        }
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('handleSaveDetail error:', error);
      toast.error('저장에 실패했습니다.');
    } finally {
      setIsActionLoading(false);
    }
  }, [selectedSalaryId, loadSalaries]);

  // ===== 지급항목 추가 핸들러 =====
  const handleAddPaymentItem = useCallback(() => {
    toast.info('지급항목 추가 기능은 준비 중입니다.');
  }, []);

  // ===== 급여 등록 핸들러 =====
  const handleCreateSalary = useCallback(async (data: {
    employeeId: number;
    employeeName: string;
    department: string;
    position: string;
    rank: string;
    year: number;
    month: number;
    baseSalary: number;
    paymentDate: string;
    allowances: Record<string, number>;
    deductions: Record<string, number>;
  }) => {
    setIsActionLoading(true);
    try {
      const result = await createSalary({
        employee_id: data.employeeId,
        year: data.year,
        month: data.month,
        base_salary: data.baseSalary,
        allowance_details: data.allowances,
        deduction_details: data.deductions,
        payment_date: data.paymentDate || undefined,
        status: 'scheduled',
      });

      if (result.success) {
        toast.success('급여가 등록되었습니다.');
        setRegistrationDialogOpen(false);
        await loadSalaries();
      } else {
        // API 실패 시 목 데이터로 로컬 추가
        const totalAllowance = Object.values(data.allowances).reduce((s, v) => s + v, 0);
        const totalDeduction = Object.values(data.deductions).reduce((s, v) => s + v, 0);
        const mockId = `mock-${Date.now()}`;
        const newRecord: SalaryRecord = {
          id: mockId,
          employeeId: String(data.employeeId),
          employeeName: data.employeeName,
          department: data.department,
          position: data.position,
          rank: data.rank,
          baseSalary: data.baseSalary,
          allowance: totalAllowance,
          overtime: data.allowances.overtime_allowance || 0,
          bonus: 0,
          deduction: totalDeduction,
          netPayment: data.baseSalary + totalAllowance - totalDeduction,
          paymentDate: data.paymentDate,
          status: 'scheduled',
          year: data.year,
          month: data.month,
          createdAt: new Date().toISOString(),
          updatedAt: new Date().toISOString(),
        };
        setSalaryData(prev => [...prev, newRecord]);
        setTotalCount(prev => prev + 1);
        toast.success('급여가 등록되었습니다. (목 데이터)');
        setRegistrationDialogOpen(false);
      }
    } catch (error) {
      if (isNextRedirectError(error)) throw error;
      console.error('handleCreateSalary error:', error);
      toast.error('급여 등록에 실패했습니다.');
    } finally {
      setIsActionLoading(false);
    }
  }, [loadSalaries]);

  // ===== 통계 카드 (총 실지급액, 총 기본급, 총 수당, 초과근무, 상여, 총공제) =====
  const statCards: StatCard[] = useMemo(() => {
    const totalNetPayment = salaryData.reduce((sum, s) => sum + s.netPayment, 0);
    const totalBaseSalary = salaryData.reduce((sum, s) => sum + s.baseSalary, 0);
    const totalAllowance = salaryData.reduce((sum, s) => sum + s.allowance, 0);
    const totalOvertime = salaryData.reduce((sum, s) => sum + s.overtime, 0);
    const totalBonus = salaryData.reduce((sum, s) => sum + s.bonus, 0);
    const totalDeduction = salaryData.reduce((sum, s) => sum + s.deduction, 0);

    return [
      {
        label: '총 실지급액',
        value: `${formatCurrency(totalNetPayment)}원`,
        icon: DollarSign,
        iconColor: 'text-green-500',
      },
      {
        label: '총 기본급',
        value: `${formatCurrency(totalBaseSalary)}원`,
        icon: Banknote,
        iconColor: 'text-blue-500',
      },
      {
        label: '총 수당',
        value: `${formatCurrency(totalAllowance)}원`,
        icon: Briefcase,
        iconColor: 'text-purple-500',
      },
      {
        label: '초과근무',
        value: `${formatCurrency(totalOvertime)}원`,
        icon: Timer,
        iconColor: 'text-orange-500',
      },
      {
        label: '상여',
        value: `${formatCurrency(totalBonus)}원`,
        icon: Gift,
        iconColor: 'text-pink-500',
      },
      {
        label: '총 공제',
        value: `${formatCurrency(totalDeduction)}원`,
        icon: MinusCircle,
        iconColor: 'text-red-500',
      },
    ];
  }, [salaryData]);

  // ===== 테이블 컬럼 (부서, 직책, 이름, 직급, 기본급, 수당, 초과근무, 상여, 공제, 실지급액, 일자, 상태, 작업) =====
  const tableColumns = useMemo(() => [
    { key: 'department', label: '부서', sortable: true },
    { key: 'position', label: '직책', sortable: true },
    { key: 'name', label: '이름', sortable: true },
    { key: 'rank', label: '직급', sortable: true },
    { key: 'baseSalary', label: '기본급', className: 'text-right', sortable: true },
    { key: 'allowance', label: '수당', className: 'text-right', sortable: true },
    { key: 'overtime', label: '초과근무', className: 'text-right', sortable: true },
    { key: 'bonus', label: '상여', className: 'text-right', sortable: true },
    { key: 'deduction', label: '공제', className: 'text-right', sortable: true },
    { key: 'netPayment', label: '실지급액', className: 'text-right', sortable: true },
    { key: 'paymentDate', label: '일자', className: 'text-center', sortable: true },
    { key: 'status', label: '상태', className: 'text-center', sortable: true },
  ], []);

  // ===== filterConfig 기반 통합 필터 시스템 =====
  const filterConfig: FilterFieldConfig[] = useMemo(() => [
    {
      key: 'sort',
      label: '정렬',
      type: 'single',
      options: Object.entries(SORT_OPTIONS).map(([value, label]) => ({
        value,
        label,
      })),
    },
  ], []);

  const filterValues: FilterValues = useMemo(() => ({
    sort: sortOption,
  }), [sortOption]);

  const handleFilterChange = useCallback((key: string, value: string | string[]) => {
    switch (key) {
      case 'sort':
        setSortOption(value as SortOption);
        break;
    }
    setCurrentPage(1);
  }, []);

  const handleFilterReset = useCallback(() => {
    setSortOption('rank');
    setCurrentPage(1);
  }, []);

  // ===== UniversalListPage 설정 =====
  const salaryConfig: UniversalListConfig<SalaryRecord> = useMemo(() => ({
    title: '급여관리',
    description: '직원들의 급여 현황을 관리합니다',
    icon: DollarSign,
    basePath: '/hr/salary-management',

    idField: 'id',

    actions: {
      getList: async () => ({
        success: true,
        data: salaryData,
        totalCount: totalCount,
        totalPages: totalPages,
      }),
    },

    columns: tableColumns,

    filterConfig: filterConfig,
    initialFilters: filterValues,
    filterTitle: '급여 필터',

    computeStats: () => statCards,

    searchPlaceholder: '이름, 부서 검색...',

    itemsPerPage: itemsPerPage,

    // 엑셀 다운로드 설정
    excelDownload: {
      columns: [
        { header: '부서', key: 'department' },
        { header: '직책', key: 'position' },
        { header: '이름', key: 'employeeName' },
        { header: '직급', key: 'rank' },
        { header: '기본급', key: 'baseSalary' },
        { header: '수당', key: 'allowance' },
        { header: '초과근무', key: 'overtime' },
        { header: '상여', key: 'bonus' },
        { header: '공제', key: 'deduction' },
        { header: '실지급액', key: 'netPayment' },
        { header: '지급일', key: 'paymentDate' },
        { header: '상태', key: 'status', transform: (value: unknown) => value === 'completed' ? '지급완료' : '지급예정' },
      ],
      filename: '급여명세',
      sheetName: '급여',
    },

    // 검색창 (공통 컴포넌트에서 자동 생성)
    hideSearch: true,
    searchValue: searchQuery,
    onSearchChange: setSearchQuery,

    // 날짜 범위 선택 (DateRangeSelector 사용)
    dateRangeSelector: {
      enabled: true,
      showPresets: false,
      startDate,
      endDate,
      onStartDateChange: setStartDate,
      onEndDateChange: setEndDate,
    },

    selectionActions: () => (
      <>
        <Button
          size="sm"
          variant="default"
          onClick={handleMarkCompleted}
          disabled={isActionLoading}
        >
          {isActionLoading ? (
            <Loader2 className="h-4 w-4 mr-2 animate-spin" />
          ) : (
            <Check className="h-4 w-4 mr-2" />
          )}
          지급완료
        </Button>
        <Button
          size="sm"
          variant="outline"
          onClick={handleMarkScheduled}
          disabled={isActionLoading}
        >
          {isActionLoading ? (
            <Loader2 className="h-4 w-4 mr-2 animate-spin" />
          ) : (
            <Clock className="h-4 w-4 mr-2" />
          )}
          지급예정
        </Button>
      </>
    ),

    headerActions: () => (
      <Button size="sm" onClick={() => setRegistrationDialogOpen(true)}>
        <Plus className="h-4 w-4 mr-1" />
        급여 등록
      </Button>
    ),

    renderTableRow: (item, index, globalIndex, handlers) => {
      const { isSelected, onToggle } = handlers;

      return (
        <TableRow
          key={item.id}
          className="cursor-pointer hover:bg-muted/50"
          onClick={() => handleViewDetail(item)}
        >
          <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
            <Checkbox checked={isSelected} onCheckedChange={onToggle} />
          </TableCell>
          <TableCell>{item.department}</TableCell>
          <TableCell>{item.position}</TableCell>
          <TableCell className="font-medium">{item.employeeName}</TableCell>
          <TableCell>{item.rank}</TableCell>
          <TableCell className="text-right">{formatCurrency(item.baseSalary)}원</TableCell>
          <TableCell className="text-right">{formatCurrency(item.allowance)}원</TableCell>
          <TableCell className="text-right">{formatCurrency(item.overtime)}원</TableCell>
          <TableCell className="text-right">{formatCurrency(item.bonus)}원</TableCell>
          <TableCell className="text-right text-red-600">-{formatCurrency(item.deduction)}원</TableCell>
          <TableCell className="text-right font-medium text-green-600">{formatCurrency(item.netPayment)}원</TableCell>
          <TableCell className="text-center">{item.paymentDate}</TableCell>
          <TableCell className="text-center">
            <Badge className={PAYMENT_STATUS_COLORS[item.status]}>
              {PAYMENT_STATUS_LABELS[item.status]}
            </Badge>
          </TableCell>
        </TableRow>
      );
    },

    renderMobileCard: (item, index, globalIndex, handlers) => {
      const { isSelected, onToggle } = handlers;

      return (
        <ListMobileCard
          id={item.id}
          title={item.employeeName}
          headerBadges={
            <Badge className={PAYMENT_STATUS_COLORS[item.status]}>
              {PAYMENT_STATUS_LABELS[item.status]}
            </Badge>
          }
          isSelected={isSelected}
          onToggleSelection={onToggle}
          onClick={() => handleViewDetail(item)}
          infoGrid={
            <div className="grid grid-cols-2 gap-3">
              <InfoField label="부서" value={item.department} />
              <InfoField label="직급" value={item.rank} />
              <InfoField label="기본급" value={`${formatCurrency(item.baseSalary)}원`} />
              <InfoField label="수당" value={`${formatCurrency(item.allowance)}원`} />
              <InfoField label="초과근무" value={`${formatCurrency(item.overtime)}원`} />
              <InfoField label="상여" value={`${formatCurrency(item.bonus)}원`} />
              <InfoField label="공제" value={`-${formatCurrency(item.deduction)}원`} />
              <InfoField label="실지급액" value={`${formatCurrency(item.netPayment)}원`} />
              <InfoField label="지급일" value={item.paymentDate} />
            </div>
          }
        />
      );
    },

    renderDialogs: (_params) => (
      <>
        <SalaryDetailDialog
          open={detailDialogOpen}
          onOpenChange={setDetailDialogOpen}
          salaryDetail={selectedSalaryDetail}
          onSave={handleSaveDetail}
        />
        <SalaryRegistrationDialog
          open={registrationDialogOpen}
          onOpenChange={setRegistrationDialogOpen}
          onSave={handleCreateSalary}
        />
      </>
    ),
  }), [
    salaryData,
    totalCount,
    totalPages,
    tableColumns,
    filterConfig,
    filterValues,
    statCards,
    startDate,
    endDate,
    handleMarkCompleted,
    handleMarkScheduled,
    isActionLoading,
    handleViewDetail,
    detailDialogOpen,
    selectedSalaryDetail,
    handleSaveDetail,
    handleAddPaymentItem,
    registrationDialogOpen,
    handleCreateSalary,
  ]);

  return (
    <UniversalListPage<SalaryRecord>
      config={salaryConfig}
      initialData={salaryData}
      initialTotalCount={totalCount}
      externalPagination={{
        currentPage,
        totalPages,
        totalItems: totalCount,
        itemsPerPage,
        onPageChange: setCurrentPage,
      }}
      externalSelection={{
        selectedItems,
        onToggleSelection: toggleSelection,
        onToggleSelectAll: toggleSelectAll,
        getItemId: (item) => item.id,
      }}
      onSearchChange={setSearchQuery}
      externalIsLoading={isLoading}
    />
  );
}