'use client';

/**
 * 인수인계보고서 관리 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
 * - Stats 카드 클릭 필터링 (activeStatTab)
 * - DateRangeSelector (headerActions → dateRangeSelector config)
 * - filterConfig (multi: 거래처, 계약담당자, 공사PM / single: 상태, 정렬)
 * - 등록 버튼 없음 (계약 종료 시 자동 등록)
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { FileText, Clock, CheckCircle, Pencil } from 'lucide-react';
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 { HandoverReport, HandoverReportStats } from './types';
import {
  REPORT_STATUS_OPTIONS,
  REPORT_SORT_OPTIONS,
  HANDOVER_STATUS_LABELS,
  HANDOVER_STATUS_STYLES,
} from './types';
import { getHandoverReportList, getHandoverReportStats } from './actions';

// 테이블 컬럼 정의
const tableColumns = [
  { key: 'no', label: '번호', className: 'w-[60px] text-center' },
  { key: 'reportNumber', label: '보고서번호', className: 'w-[100px]' },
  { key: 'partnerName', label: '거래처', className: 'w-[100px]' },
  { key: 'siteName', label: '현장명', className: 'min-w-[100px]' },
  { key: 'contractManager', label: '계약담당자', className: 'w-[100px] text-center' },
  { key: 'constructionPM', label: '공사PM', className: 'w-[80px] text-center' },
  { key: 'totalSites', label: '총 개소', className: 'w-[80px] text-center' },
  { key: 'contractAmount', label: '계약금액(공급가액)', className: 'w-[140px] text-right' },
  { key: 'contractPeriod', label: '계약기간', className: 'w-[180px] text-center' },
  { key: 'status', label: '상태', className: 'w-[100px] text-center' },
  { key: 'actions', label: '작업', className: 'w-[80px] text-center' },
];

// 목업 거래처 목록
const MOCK_PARTNERS = [
  { value: 'partner1', label: '주식회사 한빛' },
  { value: 'partner2', label: '대성건설' },
  { value: 'partner3', label: '삼성물산' },
  { value: 'partner4', label: 'LG전자' },
];

// 목업 계약담당자 목록
const MOCK_CONTRACT_MANAGERS = [
  { value: 'hong', label: '홍길동' },
  { value: 'kim', label: '김철수' },
  { value: 'lee', label: '이영희' },
];

// 목업 공사PM 목록
const MOCK_CONSTRUCTION_PMS = [
  { value: 'kim', label: '김PM' },
  { value: 'lee', label: '이PM' },
  { value: 'park', label: '박PM' },
];

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

// 날짜 포맷팅
function formatDate(dateStr: string | null): string {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date
    .toLocaleDateString('ko-KR', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    })
    .replace(/\. /g, '-')
    .replace('.', '');
}

// 계약기간 포맷팅
function formatPeriod(startDate: string | null, endDate: string | null): string {
  const start = formatDate(startDate);
  const end = formatDate(endDate);
  if (start === '-' && end === '-') return '-';
  return `${start} ~ ${end}`;
}

interface HandoverReportListClientProps {
  initialData?: HandoverReport[];
  initialStats?: HandoverReportStats;
}

export default function HandoverReportListClient({
  initialData = [],
  initialStats,
}: HandoverReportListClientProps) {
  const router = useRouter();

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

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

  // ===== 핸들러 =====
  const handleRowClick = useCallback(
    (report: HandoverReport) => {
      router.push(`/ko/construction/project/contract/handover-report/${report.id}?mode=view`);
    },
    [router]
  );

  const handleEdit = useCallback(
    (report: HandoverReport) => {
      router.push(`/ko/construction/project/contract/handover-report/${report.id}?mode=edit`);
    },
    [router]
  );

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<HandoverReport> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '인수인계보고서관리',
      description: '계약이 종료 상태 시 인수인계보고서 자동 등록',
      icon: FileText,
      basePath: '/construction/project/contract/handover-report',

      // ID 추출
      idField: 'id',

      // API 액션
      actions: {
        getList: async () => {
          const result = await getHandoverReportList({
            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 };
        },
      },

      // 테이블 컬럼
      columns: tableColumns,

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

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

      // 필터 설정
      filterConfig: [
        {
          key: 'partner',
          label: '거래처',
          type: 'multi',
          options: MOCK_PARTNERS,
        },
        {
          key: 'contractManager',
          label: '계약담당자',
          type: 'multi',
          options: MOCK_CONTRACT_MANAGERS,
        },
        {
          key: 'constructionPM',
          label: '공사PM',
          type: 'multi',
          options: MOCK_CONSTRUCTION_PMS,
        },
        {
          key: 'status',
          label: '상태',
          type: 'single',
          options: REPORT_STATUS_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'sortBy',
          label: '정렬',
          type: 'single',
          options: REPORT_SORT_OPTIONS,
        },
      ],
      initialFilters: {
        partner: [],
        contractManager: [],
        constructionPM: [],
        status: 'all',
        sortBy: 'contractDateDesc',
      },
      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 contractManagerFilters = filterValues.contractManager as string[];
          if (contractManagerFilters?.length > 0 && !contractManagerFilters.includes(item.contractManagerId))
            return false;

          // 공사PM 필터
          const constructionPMFilters = filterValues.constructionPM as string[];
          if (constructionPMFilters?.length > 0 && !constructionPMFilters.includes(item.constructionPMId || ''))
            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) || 'contractDateDesc';

        switch (sortBy) {
          case 'contractDateDesc':
            sorted.sort((a, b) => {
              if (!a.contractStartDate) return 1;
              if (!b.contractStartDate) return -1;
              return new Date(b.contractStartDate).getTime() - new Date(a.contractStartDate).getTime();
            });
            break;
          case 'contractDateAsc':
            sorted.sort((a, b) => {
              if (!a.contractStartDate) return 1;
              if (!b.contractStartDate) return -1;
              return new Date(a.contractStartDate).getTime() - new Date(b.contractStartDate).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,
      },

      // Stats 카드
      computeStats: (): StatCard[] => [
        {
          label: '전체 인수인계보고서',
          value: stats?.total ?? 0,
          icon: FileText,
          iconColor: 'text-blue-600',
          onClick: () => setActiveStatTab('all'),
          isActive: activeStatTab === 'all',
        },
        {
          label: '인수인계대기',
          value: stats?.pending ?? 0,
          icon: Clock,
          iconColor: 'text-orange-500',
          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: HandoverReport,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<HandoverReport>
      ) => (
        <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.reportNumber}</TableCell>
          <TableCell>{item.partnerName}</TableCell>
          <TableCell>{item.siteName}</TableCell>
          <TableCell className="text-center">{item.contractManagerName}</TableCell>
          <TableCell className="text-center">{item.constructionPMName || '-'}</TableCell>
          <TableCell className="text-center">{item.totalSites}</TableCell>
          <TableCell className="text-right">{formatAmount(item.contractAmount)}</TableCell>
          <TableCell className="text-center">
            {formatPeriod(item.contractStartDate, item.contractEndDate)}
          </TableCell>
          <TableCell className="text-center">
            <span className={HANDOVER_STATUS_STYLES[item.status]}>
              {HANDOVER_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>
              </div>
            )}
          </TableCell>
        </TableRow>
      ),

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: HandoverReport,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<HandoverReport>
      ) => (
        <MobileCard
          key={item.id}
          title={item.siteName}
          subtitle={item.reportNumber}
          badge={HANDOVER_STATUS_LABELS[item.status]}
          badgeVariant="secondary"
          isSelected={handlers.isSelected}
          onToggle={handlers.onToggle}
          onClick={() => handleRowClick(item)}
          details={[
            { label: '거래처', value: item.partnerName },
            { label: '계약금액', value: `${formatAmount(item.contractAmount)}원` },
            { label: '계약담당자', value: item.contractManagerName },
            { label: '총 개소', value: `${item.totalSites}개소` },
          ]}
        />
      ),
    }),
    [startDate, endDate, searchQuery, activeStatTab, stats, handleRowClick, handleEdit]
  );

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