'use client';

/**
 * 노임관리 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
 * - Stats 카드 (클릭 필터 없음, 단순 표시)
 * - DateRangeSelector + 등록 버튼 (dateRangeSelector + createButton)
 * - filterConfig (single 3개: category, status, sortBy)
 * - 삭제 기능 (deleteConfirmMessage)
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import { format, startOfYear, endOfYear } from 'date-fns';
import { useListHandlers } from '@/hooks/useListHandlers';
import { Hammer, Pencil, Trash2, HardHat } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { MobileCard } from '@/components/organisms/MobileCard';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
} from '@/components/templates/UniversalListPage';
import type { Labor, LaborStats } from './types';
import { CATEGORY_OPTIONS, STATUS_OPTIONS, SORT_OPTIONS, DEFAULT_PAGE_SIZE } from './constants';
import { getLaborList, deleteLabor, deleteLaborBulk, getLaborStats } from './actions';
import { formatNumber } from '@/lib/utils/amount';

// 테이블 컬럼 정의
const tableColumns = [
  { key: 'no', label: '번호', className: 'w-[60px] text-center' },
  { key: 'laborNumber', label: '노임번호', className: 'w-[120px]', copyable: true },
  { key: 'category', label: '구분', className: 'w-[100px] text-center', copyable: true },
  { key: 'minM', label: '최소 M', className: 'w-[100px] text-right', copyable: true },
  { key: 'maxM', label: '최대 M', className: 'w-[100px] text-right', copyable: true },
  { key: 'laborPrice', label: '노임단가', className: 'w-[120px] text-right', copyable: true },
  { key: 'status', label: '상태', className: 'w-[80px] text-center' },
  { key: 'actions', label: '작업', className: 'w-[100px] text-center' },
];

interface LaborManagementClientProps {
  initialData?: Labor[];
  initialStats?: LaborStats;
}

export default function LaborManagementClient({
  initialData = [],
  initialStats,
}: LaborManagementClientProps) {
  // ===== 공통 핸들러 Hook =====
  const { handleRowClick, handleEdit, router } = useListHandlers<Labor>(
    'construction/order/base-info/labor'
  );
  const today = new Date();

  // ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
  const [startDate, setStartDate] = useState(format(startOfYear(today), 'yyyy-MM-dd'));
  const [endDate, setEndDate] = useState(format(endOfYear(today), 'yyyy-MM-dd'));
  const [stats, setStats] = useState<LaborStats>(initialStats ?? { total: 0, active: 0 });
  const [searchQuery, setSearchQuery] = useState('');

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

  // 상태 배지 색상
  const getStatusBadgeVariant = useCallback((status: string) => {
    switch (status) {
      case '사용':
        return 'default';
      case '중지':
        return 'destructive';
      default:
        return 'outline';
    }
  }, []);

  // 가격 포맷
  const formatPrice = useCallback((price: number | null) => {
    if (price === null || price === 0) return '-';
    return formatNumber(price);
  }, []);

  // M 값 포맷
  const formatM = useCallback((value: number) => {
    if (value === 0) return '-';
    return value.toFixed(2);
  }, []);

  // ===== 추가 핸들러 =====
  const handleCreate = useCallback(() => {
    router.push('/ko/construction/order/base-info/labor?mode=new');
  }, [router]);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Labor> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '노임관리',
      description: '노임을 등록하고 관리합니다.',
      icon: Hammer,
      basePath: '/construction/order/base-info/labor',

      // ID 추출
      idField: 'id',

      // API 액션
      actions: {
        getList: async () => {
          const result = await getLaborList({
            category: 'all',
            status: 'all',
            sortOrder: '최신순',
            startDate,
            endDate,
          });
          if (result.success && result.data) {
            return {
              success: true,
              data: result.data,
              totalCount: result.data.length,
            };
          }
          return { success: false, error: result.error };
        },
        deleteItem: async (id: string) => {
          const result = await deleteLabor(id);
          return { success: result.success, error: result.error };
        },
        deleteBulk: async (ids: string[]) => {
          const result = await deleteLaborBulk(ids);
          return { success: result.success, error: result.error };
        },
      },

      // 테이블 컬럼
      columns: tableColumns,

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

      // 검색 필터
      searchPlaceholder: '노임번호, 구분 검색',
      searchFilter: (item, searchValue) => {
        const search = searchValue.toLowerCase();
        return (
          item.laborNumber.toLowerCase().includes(search) ||
          item.category.toLowerCase().includes(search)
        );
      },

      // 필터 설정
      filterConfig: [
        {
          key: 'category',
          label: '구분',
          type: 'single',
          options: CATEGORY_OPTIONS.filter((o) => o.value !== 'all').map((o) => ({
            value: o.value,
            label: o.label,
          })),
        },
        {
          key: 'status',
          label: '상태',
          type: 'single',
          options: STATUS_OPTIONS.filter((o) => o.value !== 'all').map((o) => ({
            value: o.value,
            label: o.label,
          })),
        },
        {
          key: 'sortBy',
          label: '정렬',
          type: 'single',
          options: SORT_OPTIONS.map((o) => ({
            value: o.value,
            label: o.label,
          })),
        },
      ],
      initialFilters: {
        category: 'all',
        status: 'all',
        sortBy: '최신순',
      },
      filterTitle: '노임 필터',

      // 커스텀 필터 함수
      customFilterFn: (items, filterValues) => {
        if (!items || items.length === 0) return items;
        return items.filter((item) => {
          // 구분 필터
          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;
          }

          return true;
        });
      },

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

        if (sortBy === '등록순') {
          sorted.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
        } else {
          // 기본: 최신순
          sorted.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
        }
        return sorted;
      },

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

      // 공통 헤더 옵션
      dateRangeSelector: {
        enabled: true,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },
      createButton: {
        label: '노임 등록',
        onClick: handleCreate,
      },

      // Stats 카드 (클릭 필터 없음)
      computeStats: (): StatCard[] => [
        {
          label: '전체 노임',
          value: stats.total,
          icon: Hammer,
          iconColor: 'text-blue-500',
        },
        {
          label: '사용 노임',
          value: stats.active,
          icon: HardHat,
          iconColor: 'text-green-500',
        },
      ],

      // 삭제 확인 메시지
      deleteConfirmMessage: {
        title: '노임 삭제',
        description: '선택한 노임을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.',
      },

      // 테이블 행 렌더링
      renderTableRow: (
        labor: Labor,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Labor>
      ) => (
        <TableRow
          key={labor.id}
          className="cursor-pointer hover:bg-muted/50"
          onClick={() => handleRowClick(labor)}
        >
          <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 className="font-medium">{labor.laborNumber}</TableCell>
          <TableCell className="text-center">
            <Badge variant="secondary">{labor.category}</Badge>
          </TableCell>
          <TableCell className="text-right">{formatM(labor.minM)}</TableCell>
          <TableCell className="text-right">{formatM(labor.maxM)}</TableCell>
          <TableCell className="text-right font-medium">{formatPrice(labor.laborPrice)}</TableCell>
          <TableCell className="text-center">
            <Badge variant={getStatusBadgeVariant(labor.status)}>{labor.status}</Badge>
          </TableCell>
          <TableCell className="text-center">
            {handlers.isSelected && (
              <div className="flex items-center justify-center gap-1">
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleEdit(labor);
                  }}
                >
                  <Pencil className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8 text-destructive hover:text-destructive"
                  onClick={(e) => {
                    e.stopPropagation();
                    handlers.onDelete?.(labor);
                  }}
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            )}
          </TableCell>
        </TableRow>
      ),

      // 모바일 카드 렌더링
      renderMobileCard: (
        labor: Labor,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Labor>
      ) => (
        <MobileCard
          key={labor.id}
          title={labor.laborNumber}
          subtitle={labor.category}
          badge={labor.status}
          badgeVariant={getStatusBadgeVariant(labor.status) as 'default' | 'secondary' | 'destructive' | 'outline'}
          isSelected={handlers.isSelected}
          onToggle={handlers.onToggle}
          onClick={() => handleRowClick(labor)}
          details={[
            { label: '최소 M', value: formatM(labor.minM) },
            { label: '최대 M', value: formatM(labor.maxM) },
            { label: '노임단가', value: formatPrice(labor.laborPrice) },
          ]}
        />
      ),
    }),
    [
      startDate,
      endDate,
      searchQuery,
      stats,
      handleRowClick,
      handleEdit,
      handleCreate,
      formatPrice,
      formatM,
      getStatusBadgeVariant,
    ]
  );

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