'use client';

/**
 * 입찰관리 리스트 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
 * - Stats 카드 클릭 필터링 (activeStatTab)
 * - DateRangeSelector (headerActions → dateRangeSelector config)
 * - filterConfig (multi: 거래처, 입찰자 / single: 상태, 정렬)
 * - 등록 버튼 없음 (견적완료 시 자동 등록)
 */

import { useState, useMemo } from 'react';
import { useStatsLoader } from '@/hooks/useStatsLoader';
import { FileText, Clock, Trophy, Pencil } 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 { Bidding, BiddingStats } from './types';
import {
  BIDDING_STATUS_OPTIONS,
  BIDDING_SORT_OPTIONS,
  BIDDING_STATUS_STYLES,
  BIDDING_STATUS_LABELS,
} from './types';
import { getBiddingList, getBiddingStats, deleteBidding, deleteBiddings } from './actions';
import { formatNumber } from '@/lib/utils/amount';
import { formatDate } from '@/lib/utils/date';

// 테이블 컬럼 정의
const tableColumns = [
  { key: 'no', label: '번호', className: 'w-[60px] text-center' },
  { key: 'biddingCode', label: '입찰번호', className: 'w-[120px]', copyable: true },
  { key: 'partnerName', label: '거래처', className: 'w-[100px]', copyable: true },
  { key: 'projectName', label: '현장명', className: 'min-w-[120px]', copyable: true },
  { key: 'bidderName', label: '입찰자', className: 'w-[80px]', copyable: true },
  { key: 'totalCount', label: '총 개소', className: 'w-[80px] text-center', copyable: true },
  { key: 'biddingAmount', label: '입찰금액', className: 'w-[120px] text-right', copyable: true },
  { key: 'bidDate', label: '입찰일', className: 'w-[100px] text-center', copyable: true },
  { key: 'submissionDate', label: '투찰일', className: 'w-[100px] text-center', copyable: true },
  { key: 'confirmDate', label: '확정일', className: 'w-[100px] text-center', copyable: true },
  { key: 'status', label: '상태', className: 'w-[80px] text-center' },
  { key: 'remarks', label: '비고', className: 'w-[120px]', copyable: true },
  { key: 'actions', label: '작업', className: 'w-[80px] text-center' },
];

// 거래처/입찰자 옵션 (다중선택용)
const MOCK_PARTNERS = [
  { value: '1', label: '이사대표' },
  { value: '2', label: '야사건설' },
  { value: '3', label: '여의건설' },
];

const MOCK_BIDDERS = [
  { value: 'hong', label: '홍길동' },
  { value: 'kim', label: '김철수' },
  { value: 'lee', label: '이영희' },
];

interface BiddingListClientProps {
  initialData?: Bidding[];
  initialStats?: BiddingStats;
}

export default function BiddingListClient({ initialData = [], initialStats }: BiddingListClientProps) {
  // ===== 공통 핸들러 Hook =====
  const { handleRowClick, handleEdit } = useListHandlers<Bidding>('construction/project/bidding');

  // ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
  // Stats 카드 클릭 필터용
  const [activeStatTab, setActiveStatTab] = useState<'all' | 'waiting' | 'awarded'>('all');
  // 날짜 범위
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  // 검색어
  const [searchQuery, setSearchQuery] = useState('');
  // Stats 데이터
  const { data: stats } = useStatsLoader(getBiddingStats, initialStats);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Bidding> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '입찰관리',
      description: '입찰을 관리합니다 (견적완료 시 자동 등록)',
      icon: FileText,
      basePath: '/construction/project/bidding',

      // ID 추출
      idField: 'id',

      // API 액션
      actions: {
        getList: async () => {
          const result = await getBiddingList({
            size: 1000,
            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 deleteBidding(id);
          return { success: result.success, error: result.error };
        },
        deleteBulk: async (ids: string[]) => {
          const result = await deleteBiddings(ids);
          return { success: result.success, error: result.error };
        },
      },

      // 테이블 컬럼
      columns: tableColumns,

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

      // 검색 필터
      searchPlaceholder: '입찰번호, 거래처, 현장명 검색',
      searchFilter: (item, searchValue) => {
        const search = searchValue.toLowerCase();
        return (
          item.projectName.toLowerCase().includes(search) ||
          item.biddingCode.toLowerCase().includes(search) ||
          item.partnerName.toLowerCase().includes(search)
        );
      },

      // 필터 설정 (PC: 인라인, 모바일: 바텀시트)
      filterConfig: [
        {
          key: 'partner',
          label: '거래처',
          type: 'multi',
          options: MOCK_PARTNERS,
        },
        {
          key: 'bidder',
          label: '입찰자',
          type: 'multi',
          options: MOCK_BIDDERS,
        },
        {
          key: 'status',
          label: '상태',
          type: 'single',
          options: BIDDING_STATUS_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'sortBy',
          label: '정렬',
          type: 'single',
          options: BIDDING_SORT_OPTIONS,
        },
      ],
      initialFilters: {
        partner: [],
        bidder: [],
        status: 'all',
        sortBy: 'biddingDateDesc',
      },
      filterTitle: '입찰 필터',

      // 커스텀 필터 함수 (activeStatTab + filterValues 기반)
      customFilterFn: (items, filterValues) => {
        if (!items || items.length === 0) return items;
        return items.filter((item) => {
          // Stats 탭 필터
          if (activeStatTab === 'waiting' && item.status !== 'waiting') return false;
          if (activeStatTab === 'awarded' && item.status !== 'awarded') return false;

          // 거래처 필터 (다중선택)
          const partnerFilters = filterValues.partner as string[];
          if (partnerFilters?.length > 0 && !partnerFilters.includes(item.partnerId)) return false;

          // 입찰자 필터 (다중선택)
          const bidderFilters = filterValues.bidder as string[];
          if (bidderFilters?.length > 0 && !bidderFilters.includes(item.bidderId)) 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) || 'biddingDateDesc';

        switch (sortBy) {
          case 'biddingDateDesc':
            sorted.sort((a, b) => {
              if (!a.biddingDate) return 1;
              if (!b.biddingDate) return -1;
              return new Date(b.biddingDate).getTime() - new Date(a.biddingDate).getTime();
            });
            break;
          case 'biddingDateAsc':
            sorted.sort((a, b) => {
              if (!a.biddingDate) return 1;
              if (!b.biddingDate) return -1;
              return new Date(a.biddingDate).getTime() - new Date(b.biddingDate).getTime();
            });
            break;
          case 'submissionDateDesc':
            sorted.sort((a, b) => {
              if (!a.submissionDate) return 1;
              if (!b.submissionDate) return -1;
              return new Date(b.submissionDate).getTime() - new Date(a.submissionDate).getTime();
            });
            break;
          case 'confirmDateDesc':
            sorted.sort((a, b) => {
              if (!a.confirmDate) return 1;
              if (!b.confirmDate) return -1;
              return new Date(b.confirmDate).getTime() - new Date(a.confirmDate).getTime();
            });
            break;
          case 'partnerNameAsc':
            sorted.sort((a, b) => a.partnerName.localeCompare(b.partnerName, 'ko'));
            break;
          case 'partnerNameDesc':
            sorted.sort((a, b) => b.partnerName.localeCompare(a.partnerName, 'ko'));
            break;
          case 'projectNameAsc':
            sorted.sort((a, b) => a.projectName.localeCompare(b.projectName, 'ko'));
            break;
          case 'projectNameDesc':
            sorted.sort((a, b) => b.projectName.localeCompare(a.projectName, 'ko'));
            break;
        }
        return sorted;
      },

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

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

      // Stats 카드 (동적 계산 with onClick)
      computeStats: (): StatCard[] => [
        {
          label: '전체 입찰',
          value: stats?.total ?? 0,
          icon: FileText,
          iconColor: 'text-blue-600',
          onClick: () => setActiveStatTab('all'),
          isActive: activeStatTab === 'all',
        },
        {
          label: '입찰대기',
          value: stats?.waiting ?? 0,
          icon: Clock,
          iconColor: 'text-orange-500',
          onClick: () => setActiveStatTab('waiting'),
          isActive: activeStatTab === 'waiting',
        },
        {
          label: '낙찰',
          value: stats?.awarded ?? 0,
          icon: Trophy,
          iconColor: 'text-green-600',
          onClick: () => setActiveStatTab('awarded'),
          isActive: activeStatTab === 'awarded',
        },
      ],

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

      // 테이블 행 렌더링
      renderTableRow: (
        item: Bidding,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Bidding>
      ) => (
        <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.biddingCode}</TableCell>
          <TableCell>{item.partnerName}</TableCell>
          <TableCell>{item.projectName}</TableCell>
          <TableCell>{item.bidderName}</TableCell>
          <TableCell className="text-center">{item.totalCount}</TableCell>
          <TableCell className="text-right">{formatNumber(item.biddingAmount)}</TableCell>
          <TableCell className="text-center">{formatDate(item.bidDate)}</TableCell>
          <TableCell className="text-center">{formatDate(item.submissionDate)}</TableCell>
          <TableCell className="text-center">{formatDate(item.confirmDate)}</TableCell>
          <TableCell className="text-center">
            <span className={BIDDING_STATUS_STYLES[item.status]}>
              {BIDDING_STATUS_LABELS[item.status]}
            </span>
          </TableCell>
          <TableCell className="truncate max-w-[120px]" title={item.remarks}>
            {item.remarks || '-'}
          </TableCell>
          <TableCell className="text-center">
            {handlers.isSelected && (
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8"
                onClick={(e) => {
                  e.stopPropagation();
                  handleEdit(item);
                }}
              >
                <Pencil className="h-4 w-4" />
              </Button>
            )}
          </TableCell>
        </TableRow>
      ),

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: Bidding,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Bidding>
      ) => (
        <MobileCard
          key={item.id}
          title={item.projectName}
          subtitle={item.biddingCode}
          badge={BIDDING_STATUS_LABELS[item.status]}
          badgeVariant="secondary"
          isSelected={handlers.isSelected}
          onToggle={handlers.onToggle}
          onClick={() => handleRowClick(item)}
          details={[
            { label: '거래처', value: item.partnerName },
            { label: '입찰금액', value: `${formatNumber(item.biddingAmount)}원` },
            { label: '입찰일자', value: formatDate(item.biddingDate) },
            { label: '총 개소', value: `${item.totalCount}` },
          ]}
        />
      ),
    }),
    [startDate, endDate, searchQuery, activeStatTab, stats, handleRowClick, handleEdit]
  );

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