'use client';

/**
 * 구조검토관리 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
 * - Stats 카드 클릭 필터링 (activeStatTab)
 * - DateRangeSelector + 등록 버튼 (headerActions → dateRangeSelector + createButton)
 * - filterConfig (multi: 거래처 / single: 상태, 정렬)
 * - 삭제 기능 (deleteConfirmMessage로 AlertDialog 대체)
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import { ClipboardCheck, Clock, CheckCircle, Pencil, Trash2 } 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 { StructureReview, StructureReviewStats } from './types';
import {
  STRUCTURE_REVIEW_STATUS_OPTIONS,
  STRUCTURE_REVIEW_SORT_OPTIONS,
  STRUCTURE_REVIEW_STATUS_STYLES,
  STRUCTURE_REVIEW_STATUS_LABELS,
} from './types';
import {
  getStructureReviewList,
  getStructureReviewStats,
  deleteStructureReview,
  deleteStructureReviews,
} from './actions';
import { formatDate } from '@/lib/utils/date';
import { useDateRange } from '@/hooks';

// 테이블 컬럼 정의
const tableColumns = [
  { key: 'no', label: '번호', className: 'w-[60px] text-center' },
  { key: 'reviewNumber', label: '검토번호', className: 'w-[100px]', copyable: true },
  { key: 'partnerName', label: '거래처', className: 'w-[100px]', copyable: true },
  { key: 'siteName', label: '현장명', className: 'min-w-[120px]', copyable: true },
  { key: 'requestDate', label: '구조검토 의뢰일', className: 'w-[120px]', copyable: true },
  { key: 'reviewCompany', label: '검토회사', className: 'w-[100px]', copyable: true },
  { key: 'reviewerName', label: '검토자', className: 'w-[80px]', copyable: true },
  { key: 'completionDate', label: '구조검토완료일', className: 'w-[120px]', copyable: true },
  { key: 'status', label: '상태', className: 'w-[80px] text-center' },
  { key: 'actions', label: '작업', className: 'w-[100px] text-center' },
];

// 목업 거래처 목록
const MOCK_PARTNERS = [
  { value: '1', label: '회사명A' },
  { value: '2', label: '회사명B' },
  { value: '3', label: '회사명C' },
];

interface StructureReviewListClientProps {
  initialData?: StructureReview[];
  initialStats?: StructureReviewStats;
}

export default function StructureReviewListClient({
  initialData = [],
  initialStats,
}: StructureReviewListClientProps) {
  // ===== 공통 핸들러 Hook =====
  const { handleRowClick, handleEdit, router } = useListHandlers<StructureReview>(
    'construction/order/structure-review'
  );

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

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

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

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<StructureReview> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '구조검토관리',
      description: '구조검토 의뢰를 관리합니다',
      icon: ClipboardCheck,
      basePath: '/construction/order/structure-review',

      // ID 추출
      idField: 'id',

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

      // 테이블 컬럼
      columns: tableColumns,

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

      // 검색 필터
      searchPlaceholder: '검토번호, 거래처, 현장명, 검토회사 검색',
      searchFilter: (item, searchValue) => {
        const search = searchValue.toLowerCase();
        return (
          item.reviewNumber.toLowerCase().includes(search) ||
          item.partnerName.toLowerCase().includes(search) ||
          item.siteName.toLowerCase().includes(search) ||
          item.reviewCompany.toLowerCase().includes(search)
        );
      },

      // 필터 설정
      filterConfig: [
        {
          key: 'partner',
          label: '거래처',
          type: 'multi',
          options: MOCK_PARTNERS,
        },
        {
          key: 'status',
          label: '상태',
          type: 'single',
          options: STRUCTURE_REVIEW_STATUS_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'sortBy',
          label: '정렬',
          type: 'single',
          options: STRUCTURE_REVIEW_SORT_OPTIONS,
        },
      ],
      initialFilters: {
        partner: [],
        status: 'all',
        sortBy: 'latest',
      },
      filterTitle: '구조검토 필터',

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

          // 거래처 필터 (다중선택)
          const partnerFilters = filterValues.partner as string[];
          if (partnerFilters?.length > 0 && !partnerFilters.includes(item.partnerId)) 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 '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 '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 'siteNameAsc':
            sorted.sort((a, b) => a.siteName.localeCompare(b.siteName, 'ko'));
            break;
          case 'siteNameDesc':
            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,
      },
      createButton: {
        label: '구조검토 등록',
        onClick: handleCreate,
      },

      // Stats 카드
      computeStats: (): StatCard[] => [
        {
          label: '전체 구조검토',
          value: stats?.total ?? 0,
          icon: ClipboardCheck,
          iconColor: 'text-blue-600',
          onClick: () => setActiveStatTab('all'),
          isActive: activeStatTab === 'all',
        },
        {
          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',
        },
      ],

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

      // 테이블 행 렌더링
      renderTableRow: (
        item: StructureReview,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<StructureReview>
      ) => (
        <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.reviewNumber}</TableCell>
          <TableCell>{item.partnerName}</TableCell>
          <TableCell>{item.siteName}</TableCell>
          <TableCell>{formatDate(item.requestDate)}</TableCell>
          <TableCell>{item.reviewCompany}</TableCell>
          <TableCell>{item.reviewerName}</TableCell>
          <TableCell>{formatDate(item.completionDate)}</TableCell>
          <TableCell className="text-center">
            <span className={STRUCTURE_REVIEW_STATUS_STYLES[item.status]}>
              {STRUCTURE_REVIEW_STATUS_LABELS[item.status]}
            </span>
          </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(item);
                  }}
                >
                  <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?.(item);
                  }}
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            )}
          </TableCell>
        </TableRow>
      ),

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: StructureReview,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<StructureReview>
      ) => (
        <MobileCard
          key={item.id}
          title={item.siteName}
          subtitle={item.reviewNumber}
          badge={STRUCTURE_REVIEW_STATUS_LABELS[item.status]}
          badgeVariant="secondary"
          isSelected={handlers.isSelected}
          onToggle={handlers.onToggle}
          onClick={() => handleRowClick(item)}
          details={[
            { label: '거래처', value: item.partnerName },
            { label: '의뢰일', value: formatDate(item.requestDate) },
            { label: '검토회사', value: item.reviewCompany },
          ]}
        />
      ),
    }),
    [startDate, endDate, activeStatTab, stats, handleRowClick, handleEdit, handleCreate, searchQuery]
  );

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