'use client';

/**
 * 단가관리 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
 * - Stats 카드 클릭 필터링 (activeStatTab)
 * - DateRangeSelector + 등록 버튼 (dateRangeSelector + createButton)
 * - 동적 컬럼 (renderCustomTableHeader + onDataChange)
 * - filterConfig (single: 품목유형, 카테고리, 규격, 구분, 상태, 정렬)
 * - 삭제 기능 (deleteConfirmMessage로 AlertDialog 대체)
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import { DollarSign, Package, CheckCircle, AlertCircle, Pencil, Trash2 } from 'lucide-react';
import { useListHandlers } from '@/hooks/useListHandlers';
import { Button } from '@/components/ui/button';
import { TableCell, TableRow, TableHead } 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 { Pricing, PricingStats, OrderItem } from './types';
import {
  ITEM_TYPE_OPTIONS,
  CATEGORY_OPTIONS,
  SPEC_OPTIONS,
  DIVISION_OPTIONS,
  STATUS_OPTIONS,
  SORT_OPTIONS,
  PRICING_STATUS_LABELS,
  PRICING_STATUS_STYLES,
} from './types';
import {
  getPricingList,
  getPricingStats,
  deletePricing,
  deletePricings,
} from './actions';
import { useDateRange } from '@/hooks';

interface PricingListClientProps {
  initialData?: Pricing[];
  initialStats?: PricingStats;
}

export default function PricingListClient({
  initialData = [],
  initialStats,
}: PricingListClientProps) {
  // ===== 공통 핸들러 Hook =====
  const { handleRowClick, handleEdit, router } = useListHandlers<Pricing>(
    'construction/order/base-info/pricing'
  );

  // ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
  const [activeStatTab, setActiveStatTab] = useState<'all' | 'in_use' | 'not_registered'>('all');
  const { startDate, endDate, setStartDate, setEndDate } = useDateRange('today');
  const [stats, setStats] = useState<PricingStats | null>(initialStats || null);
  const [pricingData, setPricingData] = useState<Pricing[]>(initialData);

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

  // 동적 항목명 컬럼 추출 (전체 데이터 기반)
  const dynamicOrderItemColumns = useMemo(() => {
    const columnSet = new Set<string>();
    pricingData.forEach((pricing) => {
      pricing.orderItems.forEach((item) => {
        columnSet.add(item.name);
      });
    });
    return Array.from(columnSet);
  }, [pricingData]);

  // 동적 항목값 가져오기
  const getOrderItemValue = useCallback((orderItems: OrderItem[], columnName: string): string => {
    const item = orderItems.find((oi) => oi.name === columnName);
    return item?.value || '-';
  }, []);

  // 숫자 포맷
  const formatNumber = useCallback((num: number) => {
    return num.toLocaleString('ko-KR');
  }, []);

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

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Pricing> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '단가관리',
      description: '단가를 등록하고 관리합니다',
      icon: DollarSign,
      basePath: '/construction/order/base-info/pricing',

      // ID 추출
      idField: 'id',

      // API 액션
      actions: {
        getList: async () => {
          const result = await getPricingList({
            startDate: startDate || undefined,
            endDate: endDate || undefined,
          });
          if (result.success && result.data) {
            return {
              success: true,
              data: result.data.items,
              totalCount: result.data.total,
            };
          }
          return { success: false, error: result.error };
        },
        deleteItem: async (id: string) => {
          const result = await deletePricing(id);
          return { success: result.success, error: result.error };
        },
        deleteBulk: async (ids: string[]) => {
          const result = await deletePricings(ids);
          return { success: result.success, error: result.error };
        },
      },

      // 빈 테이블 컬럼 (동적 컬럼은 renderCustomTableHeader에서 처리)
      columns: [],

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

      // 데이터 변경 콜백 (동적 컬럼 계산용)
      onDataChange: (data) => setPricingData(data),

      // 검색 필터
      searchPlaceholder: '단가번호, 품목명, 카테고리, 거래처 검색',
      searchFilter: (item, searchValue) => {
        const search = searchValue.toLowerCase();
        return (
          item.pricingNumber.toLowerCase().includes(search) ||
          item.itemName.toLowerCase().includes(search) ||
          item.category.toLowerCase().includes(search) ||
          item.vendor.toLowerCase().includes(search)
        );
      },

      // 필터 설정
      filterConfig: [
        {
          key: 'itemType',
          label: '품목유형',
          type: 'single',
          options: ITEM_TYPE_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'category',
          label: '카테고리',
          type: 'single',
          options: CATEGORY_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'spec',
          label: '규격',
          type: 'single',
          options: SPEC_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'division',
          label: '구분',
          type: 'single',
          options: DIVISION_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'status',
          label: '상태',
          type: 'single',
          options: STATUS_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'sortBy',
          label: '정렬',
          type: 'single',
          options: SORT_OPTIONS,
        },
      ],
      initialFilters: {
        itemType: 'all',
        category: 'all',
        spec: 'all',
        division: 'all',
        status: 'all',
        sortBy: 'latest',
      },
      filterTitle: '단가 필터',

      // 커스텀 필터 함수
      customFilterFn: (items, filterValues) => {
        return items.filter((item) => {
          // Stats 탭 필터
          if (activeStatTab === 'in_use' && item.status !== 'in_use') return false;
          if (activeStatTab === 'not_registered' && item.status !== 'not_registered') return false;

          // 품목유형 필터
          const itemTypeFilter = filterValues.itemType as string;
          if (itemTypeFilter && itemTypeFilter !== 'all') {
            const typeMap: Record<string, string> = {
              box: '박스',
              parts: '부속',
              consumables: '소모품',
              utility: '공과',
            };
            if (item.itemType !== typeMap[itemTypeFilter]) return false;
          }

          // 카테고리 필터
          const categoryFilter = filterValues.category as string;
          if (categoryFilter && categoryFilter !== 'all') {
            const categoryMap: Record<string, string> = {
              steel: '철물',
              electrical: '전기',
              plumbing: '배관',
              interior: '내장',
            };
            if (item.category !== categoryMap[categoryFilter]) return false;
          }

          // 규격 필터
          const specFilter = filterValues.spec as string;
          if (specFilter && specFilter !== 'all' && item.spec !== specFilter) return false;

          // 구분 필터
          const divisionFilter = filterValues.division as string;
          if (divisionFilter && divisionFilter !== 'all') {
            const divisionMap: Record<string, string> = {
              domestic: '국산',
              imported: '수입',
            };
            if (item.division !== divisionMap[divisionFilter]) 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) || 'latest';

        switch (sortBy) {
          case 'oldest':
            sorted.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
            break;
          case 'price_high':
            sorted.sort((a, b) => b.sellingPrice - a.sellingPrice);
            break;
          case 'price_low':
            sorted.sort((a, b) => a.sellingPrice - b.sellingPrice);
            break;
          default: // latest
            sorted.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
            break;
        }
        return sorted;
      },

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

      // Stats 카드
      computeStats: (): StatCard[] => [
        {
          label: '전체 단가',
          value: stats?.total ?? 0,
          icon: Package,
          iconColor: 'text-gray-600',
          onClick: () => setActiveStatTab('all'),
          isActive: activeStatTab === 'all',
        },
        {
          label: '사용 단가',
          value: stats?.inUse ?? 0,
          icon: CheckCircle,
          iconColor: 'text-green-600',
          onClick: () => setActiveStatTab('in_use'),
          isActive: activeStatTab === 'in_use',
        },
        {
          label: '미등록 단가',
          value: stats?.notRegistered ?? 0,
          icon: AlertCircle,
          iconColor: 'text-gray-400',
          onClick: () => setActiveStatTab('not_registered'),
          isActive: activeStatTab === 'not_registered',
        },
      ],

      // 삭제 확인 메시지 (AlertDialog 대체)
      deleteConfirmMessage: {
        title: '단가 삭제',
        description: '선택한 단가를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.',
      },

      // 커스텀 테이블 헤더 (동적 컬럼)
      renderCustomTableHeader: ({ displayData, selectedItems, onToggleSelectAll }) => (
        <>
          <TableHead className="w-[40px] text-center">
            <Checkbox
              checked={selectedItems.size === displayData.length && displayData.length > 0}
              onCheckedChange={onToggleSelectAll}
            />
          </TableHead>
          <TableHead className="w-[50px] text-center">번호</TableHead>
          <TableHead className="w-[120px]">단가번호</TableHead>
          <TableHead className="w-[80px]">품목유형</TableHead>
          <TableHead className="w-[140px]">카테고리</TableHead>
          <TableHead className="min-w-[120px]">품목명</TableHead>
          <TableHead className="w-[100px]">규격</TableHead>
          {/* 동적 항목명 컬럼 */}
          {dynamicOrderItemColumns.map((colName) => (
            <TableHead key={colName} className="w-[80px]">
              {colName}
            </TableHead>
          ))}
          <TableHead className="w-[60px]">단위</TableHead>
          <TableHead className="w-[60px]">구분</TableHead>
          <TableHead className="w-[120px]">거래처</TableHead>
          <TableHead className="w-[100px] text-right">판매단가</TableHead>
          <TableHead className="w-[70px] text-center">상태</TableHead>
          {selectedItems.size > 0 && (
            <TableHead className="w-[100px] text-center">작업</TableHead>
          )}
        </>
      ),

      // 테이블 행 렌더링
      renderTableRow: (
        pricing: Pricing,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Pricing>
      ) => (
        <TableRow
          key={pricing.id}
          className="cursor-pointer hover:bg-muted/50"
          onClick={() => handleRowClick(pricing)}
        >
          <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>{pricing.pricingNumber}</TableCell>
          <TableCell>{pricing.itemType}</TableCell>
          <TableCell>{pricing.category}</TableCell>
          <TableCell>{pricing.itemName}</TableCell>
          <TableCell>{pricing.spec}</TableCell>
          {/* 동적 항목명 값 */}
          {dynamicOrderItemColumns.map((colName) => (
            <TableCell key={colName}>
              {getOrderItemValue(pricing.orderItems, colName)}
            </TableCell>
          ))}
          <TableCell>{pricing.unit}</TableCell>
          <TableCell>{pricing.division}</TableCell>
          <TableCell>{pricing.vendor}</TableCell>
          <TableCell className="text-right">{formatNumber(pricing.sellingPrice)}</TableCell>
          <TableCell className="text-center">
            <Badge className={PRICING_STATUS_STYLES[pricing.status]}>
              {PRICING_STATUS_LABELS[pricing.status]}
            </Badge>
          </TableCell>
          {handlers.isSelected && (
            <TableCell className="text-center">
              <div className="flex items-center justify-center gap-1">
                <Button
                  variant="ghost"
                  size="icon"
                  className="h-8 w-8"
                  onClick={(e) => {
                    e.stopPropagation();
                    handleEdit(pricing);
                  }}
                >
                  <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?.(pricing);
                  }}
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            </TableCell>
          )}
        </TableRow>
      ),

      // 모바일 카드 렌더링
      renderMobileCard: (
        pricing: Pricing,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Pricing>
      ) => (
        <MobileCard
          key={pricing.id}
          title={pricing.itemName}
          subtitle={pricing.pricingNumber}
          badge={PRICING_STATUS_LABELS[pricing.status]}
          badgeVariant="secondary"
          isSelected={handlers.isSelected}
          onToggle={handlers.onToggle}
          onClick={() => handleRowClick(pricing)}
          details={[
            { label: '품목유형', value: pricing.itemType },
            { label: '카테고리', value: pricing.category },
            { label: '판매단가', value: formatNumber(pricing.sellingPrice) },
          ]}
        />
      ),
    }),
    [
      startDate,
      endDate,
      activeStatTab,
      stats,
      dynamicOrderItemColumns,
      handleRowClick,
      handleEdit,
      handleCreate,
      getOrderItemValue,
      formatNumber,
    ]
  );

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