'use client';

/**
 * 작업지시 목록 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 서버 사이드 페이지네이션 (getWorkOrders API)
 * - 통계 카드 (getWorkOrderStats API)
 * - 탭 기반 상태 필터링
 */

import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Plus, FileText, Calendar, Users, CheckCircle2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type TabOption,
  type StatCard,
  type ListParams,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { toast } from 'sonner';
import { getWorkOrders, getWorkOrderStats } from './actions';
import {
  WORK_ORDER_STATUS_LABELS,
  WORK_ORDER_STATUS_COLORS,
  type WorkOrder,
  type WorkOrderStats,
} from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';

// 탭 필터 정의
type TabFilter = 'all' | 'unassigned' | 'pending' | 'waiting' | 'in_progress' | 'completed';

// 페이지당 항목 수
const ITEMS_PER_PAGE = 20;

// 작업자 표시 포맷 (홍길동 외 2명)
function formatAssignees(item: WorkOrder): string {
  if (item.assignees && item.assignees.length > 0) {
    const primaryAssignee = item.assignees.find(a => a.isPrimary) || item.assignees[0];
    const otherCount = item.assignees.length - 1;
    if (otherCount > 0) {
      return `${primaryAssignee.name} 외 ${otherCount}명`;
    }
    return primaryAssignee.name;
  }
  return item.assignee || '-';
}

export function WorkOrderList() {
  const router = useRouter();

  // ===== 통계 데이터 (외부 관리 - 별도 API) =====
  const [statsData, setStatsData] = useState<WorkOrderStats>({
    total: 0,
    unassigned: 0,
    pending: 0,
    waiting: 0,
    inProgress: 0,
    completed: 0,
  });

  // 통계 데이터 로드 (초기 1회)
  useEffect(() => {
    const loadStats = async () => {
      try {
        const result = await getWorkOrderStats();
        if (result.success && result.data) {
          setStatsData(result.data);
        }
      } catch (error) {
        if (isNextRedirectError(error)) throw error;
        console.error('[WorkOrderList] loadStats error:', error);
      }
    };
    loadStats();
  }, []);

  // ===== 행 클릭 핸들러 =====
  const handleRowClick = useCallback(
    (item: WorkOrder) => {
      router.push(`/ko/production/work-orders/${item.id}?mode=view`);
    },
    [router]
  );

  // ===== 등록 핸들러 =====
  const handleCreate = useCallback(() => {
    router.push('/ko/production/work-orders?mode=new');
  }, [router]);

  // ===== 탭 옵션 (통계 데이터 기반) =====
  const tabs: TabOption[] = useMemo(
    () => [
      { value: 'all', label: '전체', count: statsData.total },
      { value: 'unassigned', label: '미배정', count: statsData.unassigned, color: 'gray' },
      { value: 'pending', label: '승인대기', count: statsData.pending, color: 'orange' },
      { value: 'waiting', label: '작업대기', count: statsData.waiting, color: 'yellow' },
      { value: 'in_progress', label: '작업중', count: statsData.inProgress, color: 'blue' },
      { value: 'completed', label: '작업완료', count: statsData.completed, color: 'green' },
    ],
    [statsData]
  );

  // ===== 통계 카드 =====
  const stats: StatCard[] = useMemo(
    () => [
      {
        label: '전체',
        value: statsData.total,
        icon: FileText,
        iconColor: 'text-gray-600',
      },
      {
        label: '미착수',
        value: statsData.waiting + statsData.unassigned + statsData.pending,
        icon: Calendar,
        iconColor: 'text-orange-600',
      },
      {
        label: '작업중',
        value: statsData.inProgress,
        icon: Users,
        iconColor: 'text-blue-600',
      },
      {
        label: '작업완료',
        value: statsData.completed,
        icon: CheckCircle2,
        iconColor: 'text-green-600',
      },
    ],
    [statsData]
  );

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<WorkOrder> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '작업지시 목록',
      description: '생산 작업지시 관리',
      icon: FileText,
      basePath: '/production/work-orders',

      // ID 추출
      idField: 'id',

      // API 액션 (서버 사이드 페이지네이션)
      actions: {
        getList: async (params?: ListParams) => {
          try {
            const result = await getWorkOrders({
              page: params?.page || 1,
              perPage: params?.pageSize || ITEMS_PER_PAGE,
              status: params?.tab === 'all' ? undefined : (params?.tab as TabFilter),
              search: params?.search || undefined,
            });

            if (result.success) {
              // 통계도 다시 로드 (탭 변경 시 최신 데이터 반영)
              const statsResult = await getWorkOrderStats();
              if (statsResult.success && statsResult.data) {
                setStatsData(statsResult.data);
              }

              return {
                success: true,
                data: result.data,
                totalCount: result.pagination.total,
                totalPages: result.pagination.lastPage,
              };
            }
            return { success: false, error: result.error };
          } catch (error) {
            if (isNextRedirectError(error)) throw error;
            return { success: false, error: '데이터 로드 중 오류가 발생했습니다.' };
          }
        },
      },

      // 테이블 컬럼
      columns: [
        { key: 'no', label: '번호', className: 'w-[60px] text-center' },
        { key: 'workOrderNo', label: '작업지시번호', className: 'min-w-[140px]' },
        { key: 'processType', label: '공정', className: 'w-[80px]' },
        { key: 'lotNo', label: '로트번호', className: 'min-w-[120px]' },
        { key: 'orderDate', label: '지시일', className: 'w-[100px]' },
        { key: 'isAssigned', label: '배정', className: 'w-[60px] text-center' },
        { key: 'hasWork', label: '작업', className: 'w-[60px] text-center' },
        { key: 'isStarted', label: '시작', className: 'w-[60px] text-center' },
        { key: 'status', label: '작업상태', className: 'w-[100px]' },
        { key: 'priority', label: '현장순위', className: 'w-[80px] text-center' },
        { key: 'assignee', label: '작업자', className: 'w-[80px]' },
        { key: 'projectName', label: '현장명', className: 'min-w-[150px]' },
        { key: 'shipmentDate', label: '출고예정일', className: 'w-[110px]' },
      ],

      // 서버 사이드 페이지네이션
      clientSideFiltering: false,
      itemsPerPage: ITEMS_PER_PAGE,

      // 검색
      searchPlaceholder: '작업지시번호, 발주처, 현장명 검색...',
      searchFilter: (item: WorkOrder, search: string) => {
        const s = search.toLowerCase();
        return (
          item.workOrderNo?.toLowerCase().includes(s) ||
          item.client?.toLowerCase().includes(s) ||
          item.projectName?.toLowerCase().includes(s) ||
          item.lotNo?.toLowerCase().includes(s) ||
          false
        );
      },

      // 탭 설정
      tabs,
      defaultTab: 'all',

      // 통계 카드
      stats,

      // 헤더 액션 (등록 버튼)
      headerActions: () => (
        <Button onClick={handleCreate}>
          <Plus className="w-4 h-4 mr-1.5" />
          등록
        </Button>
      ),

      // 테이블 행 렌더링
      renderTableRow: (
        item: WorkOrder,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<WorkOrder>
      ) => {
        return (
          <TableRow
            key={item.id}
            className={`cursor-pointer hover:bg-muted/50 ${handlers.isSelected ? 'bg-blue-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 className="font-medium">{item.workOrderNo}</TableCell>
            <TableCell>{item.processName}</TableCell>
            <TableCell>{item.lotNo}</TableCell>
            <TableCell>{item.orderDate}</TableCell>
            <TableCell className="text-center">{item.isAssigned ? 'Y' : '-'}</TableCell>
            <TableCell className="text-center">
              {item.status !== 'unassigned' && item.status !== 'pending' ? 'Y' : '-'}
            </TableCell>
            <TableCell className="text-center">{item.isStarted ? 'Y' : '-'}</TableCell>
            <TableCell>
              <Badge className={`${WORK_ORDER_STATUS_COLORS[item.status]} border-0`}>
                {WORK_ORDER_STATUS_LABELS[item.status]}
              </Badge>
            </TableCell>
            <TableCell className="text-center">{item.priority}</TableCell>
            <TableCell>{formatAssignees(item)}</TableCell>
            <TableCell className="max-w-[200px] truncate">{item.projectName}</TableCell>
            <TableCell>{item.shipmentDate}</TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: WorkOrder,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<WorkOrder>
      ) => {
        return (
          <ListMobileCard
            key={item.id}
            id={item.id}
            isSelected={handlers.isSelected}
            onToggleSelection={handlers.onToggle}
            onClick={() => handleRowClick(item)}
            headerBadges={
              <>
                <Badge variant="outline" className="text-xs">
                  #{globalIndex}
                </Badge>
                <Badge variant="outline" className="text-xs">
                  {item.workOrderNo}
                </Badge>
              </>
            }
            title={item.projectName}
            statusBadge={
              <Badge className={`${WORK_ORDER_STATUS_COLORS[item.status]} border-0`}>
                {WORK_ORDER_STATUS_LABELS[item.status]}
              </Badge>
            }
            infoGrid={
              <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                <InfoField label="공정" value={item.processName} />
                <InfoField label="로트번호" value={item.lotNo} />
                <InfoField label="발주처" value={item.client} />
                <InfoField label="작업자" value={formatAssignees(item)} />
                <InfoField label="지시일" value={item.orderDate} />
                <InfoField label="출고예정일" value={item.shipmentDate} />
                <InfoField label="현장순위" value={item.priority} />
              </div>
            }
          />
        );
      },
    }),
    [tabs, stats, handleRowClick, handleCreate]
  );

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