'use client';

/**
 * 작업인력현황 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
 * - Stats 카드 클릭 필터링 (activeStatTab)
 * - DateRangeSelector (headerActions → dateRangeSelector config)
 * - filterConfig (multi: 거래처, 현장, 부서, 이름 / single: 구분, 상태, 정렬)
 * - 등록/삭제 버튼 없음 (조회 전용)
 */

import { useState, useMemo, useEffect } from 'react';
import { Users, Eye, FileText, Clock, CheckCircle } from 'lucide-react';
import { useListHandlers } from '@/hooks/useListHandlers';
import { Button } from '@/components/ui/button';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { MobileCard } from '@/components/organisms/MobileCard';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
} from '@/components/templates/UniversalListPage';
import type { WorkerStatus, WorkerStatusStats } from './types';
import {
  WORKER_CATEGORY_OPTIONS,
  WORKER_CATEGORY_LABELS,
  WORKER_STATUS_OPTIONS,
  WORKER_STATUS_LABELS,
  WORKER_STATUS_STYLES,
  WORKER_SORT_OPTIONS,
  MOCK_WORKER_PARTNERS,
  MOCK_WORKER_SITES,
  MOCK_WORKER_DEPARTMENTS,
  MOCK_WORKER_NAMES,
} from './types';
import { getWorkerStatusList, getWorkerStatusStats } from './actions';
import { useDateRange } from '@/hooks';

// 테이블 컬럼 정의
const tableColumns = [
  { key: 'no', label: '번호', className: 'w-[50px] text-center' },
  { key: 'partnerName', label: '거래처', className: 'w-[100px]', copyable: true },
  { key: 'siteName', label: '현장', className: 'min-w-[100px]', copyable: true },
  { key: 'category', label: '구분', className: 'w-[80px] text-center', copyable: true },
  { key: 'department', label: '부서', className: 'w-[80px]', copyable: true },
  { key: 'workerName', label: '이름', className: 'w-[80px]', copyable: true },
  { key: 'baseDate', label: '기준일', className: 'w-[100px]', copyable: true },
  { key: 'checkInTime', label: '출근', className: 'w-[80px] text-center', copyable: true },
  { key: 'checkOutTime', label: '퇴근', className: 'w-[80px] text-center', copyable: true },
  { key: 'constructionNumber', label: '시공번호', className: 'w-[120px]', copyable: true },
  { key: 'laborCost', label: '노임', className: 'w-[100px] text-right', copyable: true },
  { key: 'status', label: '상태', className: 'w-[80px] text-center' },
  { key: 'actions', label: '작업', className: 'w-[60px] text-center' },
];

// 시간 포맷
function formatTime(timeStr: string | null): string {
  if (!timeStr) return '-';
  return timeStr;
}

// 금액 포맷
function formatCurrency(amount: number): string {
  return new Intl.NumberFormat('ko-KR').format(amount);
}

interface WorkerStatusListClientProps {
  initialData?: WorkerStatus[];
  initialStats?: WorkerStatusStats;
}

export default function WorkerStatusListClient({
  initialData = [],
  initialStats,
}: WorkerStatusListClientProps) {
  // ===== 공통 핸들러 Hook =====
  const { handleRowClick } = useListHandlers<WorkerStatus>('construction/project/worker-status');

  // ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
  const [activeStatTab, setActiveStatTab] = useState<'all' | 'all_contract' | 'pending' | 'completed'>('all');
  const { startDate, endDate, setStartDate, setEndDate } = useDateRange('today');
  const [stats, setStats] = useState<WorkerStatusStats | null>(initialStats || null);
  const [searchQuery, setSearchQuery] = useState('');

  // Stats 로드
  useEffect(() => {
    if (!initialStats) {
      getWorkerStatusStats().then((result) => {
        if (result.success && result.data) {
          setStats(result.data);
        }
      });
    }
  }, [initialStats]);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<WorkerStatus> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '작업인력현황',
      description: '작업인력현황을 확인합니다',
      icon: Users,
      basePath: '/construction/project/worker-status',

      // ID 추출
      idField: 'id',

      // API 액션
      actions: {
        getList: async () => {
          const result = await getWorkerStatusList({
            size: 1000,
            startDate: startDate || undefined,
            endDate: endDate || undefined,
          });
          if (result.success && result.data) {
            return {
              success: true,
              data: result.data.items,
              totalCount: result.data.totalItems,
            };
          }
          return { success: false, error: result.error };
        },
      },

      // 테이블 컬럼
      columns: tableColumns,

      // 클라이언트 사이드 필터링
      clientSideFiltering: true,
      itemsPerPage: 20,

      // 검색 필터
      searchPlaceholder: '거래처, 현장, 부서, 이름, 시공번호 검색',
      searchFilter: (item, searchValue) => {
        const search = searchValue.toLowerCase();
        return (
          item.partnerName.toLowerCase().includes(search) ||
          item.siteName.toLowerCase().includes(search) ||
          item.department.toLowerCase().includes(search) ||
          item.workerName.toLowerCase().includes(search) ||
          item.constructionNumber.toLowerCase().includes(search)
        );
      },

      // 필터 설정
      filterConfig: [
        {
          key: 'partner',
          label: '거래처',
          type: 'multi',
          options: MOCK_WORKER_PARTNERS,
        },
        {
          key: 'site',
          label: '현장명',
          type: 'multi',
          options: MOCK_WORKER_SITES,
        },
        {
          key: 'category',
          label: '구분',
          type: 'single',
          options: WORKER_CATEGORY_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'department',
          label: '부서',
          type: 'multi',
          options: MOCK_WORKER_DEPARTMENTS,
        },
        {
          key: 'name',
          label: '이름',
          type: 'multi',
          options: MOCK_WORKER_NAMES,
        },
        {
          key: 'status',
          label: '상태',
          type: 'single',
          options: WORKER_STATUS_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'sortBy',
          label: '정렬',
          type: 'single',
          options: WORKER_SORT_OPTIONS,
        },
      ],
      initialFilters: {
        partner: [],
        site: [],
        category: 'all',
        department: [],
        name: [],
        status: 'all',
        sortBy: 'latest',
      },
      filterTitle: '작업인력 필터',

      // 커스텀 필터 함수
      customFilterFn: (items, filterValues) => {
        if (!items || items.length === 0) return items;
        return items.filter((item) => {
          // Stats 탭 필터 (계약상태)
          if (activeStatTab !== 'all' && item.contractStatus !== activeStatTab) return false;

          // 구분 필터
          const categoryFilter = filterValues.category as string;
          if (categoryFilter && categoryFilter !== 'all' && item.category !== categoryFilter) return false;

          // 상태 필터 (출근상태)
          const statusFilter = filterValues.status as string;
          if (statusFilter && statusFilter !== 'all' && item.status !== statusFilter) return false;

          // 거래처 필터 (다중선택)
          const partnerFilters = filterValues.partner as string[];
          if (partnerFilters?.length > 0) {
            const matchingPartner = MOCK_WORKER_PARTNERS.find((p) => p.label === item.partnerName);
            if (!matchingPartner || !partnerFilters.includes(matchingPartner.value)) {
              return false;
            }
          }

          // 현장 필터 (다중선택)
          const siteFilters = filterValues.site as string[];
          if (siteFilters?.length > 0) {
            const matchingSite = MOCK_WORKER_SITES.find((s) => s.label === item.siteName);
            if (!matchingSite || !siteFilters.includes(matchingSite.value)) {
              return false;
            }
          }

          // 부서 필터 (다중선택)
          const departmentFilters = filterValues.department as string[];
          if (departmentFilters?.length > 0) {
            const matchingDept = MOCK_WORKER_DEPARTMENTS.find((d) => d.label === item.department);
            if (!matchingDept || !departmentFilters.includes(matchingDept.value)) {
              return false;
            }
          }

          // 이름 필터 (다중선택)
          const nameFilters = filterValues.name as string[];
          if (nameFilters?.length > 0) {
            const matchingName = MOCK_WORKER_NAMES.find((n) => n.label === item.workerName);
            if (!matchingName || !nameFilters.includes(matchingName.value)) {
              return false;
            }
          }

          return true;
        });
      },

      // 커스텀 정렬 함수
      customSortFn: (items, filterValues) => {
        const sorted = [...items];
        const sortBy = (filterValues.sortBy as string) || 'latest';

        switch (sortBy) {
          case 'latest':
            sorted.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
            break;
          case 'oldest':
            sorted.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
            break;
          case 'partnerAsc':
            sorted.sort((a, b) => a.partnerName.localeCompare(b.partnerName, 'ko'));
            break;
          case 'partnerDesc':
            sorted.sort((a, b) => b.partnerName.localeCompare(a.partnerName, 'ko'));
            break;
          case 'siteAsc':
            sorted.sort((a, b) => a.siteName.localeCompare(b.siteName, 'ko'));
            break;
          case 'siteDesc':
            sorted.sort((a, b) => b.siteName.localeCompare(a.siteName, 'ko'));
            break;
        }
        return sorted;
      },

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

      // 공통 헤더 옵션
      dateRangeSelector: {
        enabled: true,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      // Stats 카드
      computeStats: (): StatCard[] => [
        {
          label: '전체 계약',
          value: stats?.allContract ?? 0,
          icon: FileText,
          iconColor: 'text-blue-600',
          onClick: () => setActiveStatTab('all_contract'),
          isActive: activeStatTab === 'all_contract',
        },
        {
          label: '계약대기',
          value: stats?.pending ?? 0,
          icon: Clock,
          iconColor: 'text-yellow-600',
          onClick: () => setActiveStatTab('pending'),
          isActive: activeStatTab === 'pending',
        },
        {
          label: '계약완료',
          value: stats?.completed ?? 0,
          icon: CheckCircle,
          iconColor: 'text-green-600',
          onClick: () => setActiveStatTab('completed'),
          isActive: activeStatTab === 'completed',
        },
      ],

      // 테이블 행 렌더링
      renderTableRow: (
        item: WorkerStatus,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<WorkerStatus>
      ) => (
        <TableRow
          key={item.id}
          className="cursor-pointer hover:bg-muted/50"
          onClick={() => handleRowClick(item)}
        >
          <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
            <Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
          </TableCell>
          <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
          <TableCell>{item.partnerName}</TableCell>
          <TableCell>{item.siteName}</TableCell>
          <TableCell className="text-center">
            <span className="px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-700">
              {WORKER_CATEGORY_LABELS[item.category]}
            </span>
          </TableCell>
          <TableCell>{item.department}</TableCell>
          <TableCell>{item.workerName}</TableCell>
          <TableCell>{item.baseDate}</TableCell>
          <TableCell className="text-center">{formatTime(item.checkInTime)}</TableCell>
          <TableCell className="text-center">{formatTime(item.checkOutTime)}</TableCell>
          <TableCell>{item.constructionNumber}</TableCell>
          <TableCell className="text-right">{formatCurrency(item.laborCost)}</TableCell>
          <TableCell className="text-center">
            <span className={`px-2 py-1 rounded-full text-xs font-medium ${WORKER_STATUS_STYLES[item.status]}`}>
              {WORKER_STATUS_LABELS[item.status]}
            </span>
          </TableCell>
          <TableCell className="text-center">
            {handlers.isSelected && (
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8"
                onClick={(e) => {
                  e.stopPropagation();
                  handleRowClick(item);
                }}
              >
                <Eye className="h-4 w-4" />
              </Button>
            )}
          </TableCell>
        </TableRow>
      ),

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: WorkerStatus,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<WorkerStatus>
      ) => (
        <MobileCard
          key={item.id}
          title={item.workerName}
          subtitle={`${item.partnerName} - ${item.siteName}`}
          badge={WORKER_STATUS_LABELS[item.status]}
          badgeVariant="secondary"
          isSelected={handlers.isSelected}
          onToggle={handlers.onToggle}
          onClick={() => handleRowClick(item)}
          details={[
            { label: '구분', value: WORKER_CATEGORY_LABELS[item.category] },
            { label: '부서', value: item.department },
            { label: '기준일', value: item.baseDate },
            { label: '노임', value: formatCurrency(item.laborCost) },
          ]}
        />
      ),
    }),
    [startDate, endDate, activeStatTab, stats, handleRowClick, searchQuery]
  );

  return <UniversalListPage config={config} initialData={initialData} onSearchChange={setSearchQuery} />;
}
