'use client';

/**
 * 작업지시 목록 - 공정 기반 동적 탭 구조
 *
 * - 탭: 전체 + 공정관리에서 가져온 동적 공정 탭 + 기타(미지정)
 * - 필터: 상태 + 우선순위
 * - 통계 카드 6개: 전체 작업 / 작업 대기 / 작업중 / 작업 완료 / 긴급 / 지연
 * - 컬럼: 작업번호/수주일/출고예정일/로트번호/수주처/현장명/틀수/상태/우선순위/부서/비고
 * - API: getProcessOptions로 공정 목록 동적 로드 → processId로 필터링
 */

import { useState, useEffect, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { FileText, Clock, Loader, CheckCircle2, AlertTriangle, TimerOff } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
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 { getWorkOrders, getWorkOrderStats, getProcessOptions } from './actions';
import type { ProcessOption } from './actions';
import {
  WORK_ORDER_STATUS_LABELS,
  WORK_ORDER_STATUS_COLORS,
  type WorkOrder,
  type WorkOrderStats,
  type WorkOrderStatus,
} from './types';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { WipProductionModal } from './WipProductionModal';
// 공통 유틸 import
import { WORK_STATUS_FILTER, COMMON_PRIORITY_FILTER } from '@/lib/constants/filter-presets';
import { getPriorityStyle } from '@/lib/utils/status-config';

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

// 특수 탭 상수
const TAB_ALL = 'all';      // 전체

// 필터 설정: 공통 프리셋 사용 (상태 + 우선순위)
const filterConfig = [WORK_STATUS_FILTER, COMMON_PRIORITY_FILTER];

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

  // ===== 활성 탭 및 재공품 모달 =====
  const [activeTab, setActiveTab] = useState(TAB_ALL);
  const [isWipModalOpen, setIsWipModalOpen] = useState(false);

  // ===== 공정 목록 (동적 탭 생성용) =====
  const [processList, setProcessList] = useState<ProcessOption[]>([]);
  const [processMapLoaded, setProcessMapLoaded] = useState(false);

  useEffect(() => {
    const loadProcessOptions = async () => {
      try {
        const result = await getProcessOptions();
        if (result.success && result.data) {
          setProcessList(result.data);
        }
      } catch (error) {
        if (isNextRedirectError(error)) throw error;
        console.error('[WorkOrderList] loadProcessOptions error:', error);
      } finally {
        setProcessMapLoaded(true);
      }
    };
    loadProcessOptions();
  }, []);

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

  // 통계 데이터 로드 (초기 1회) + 탭 카운트 세팅
  useEffect(() => {
    const loadStats = async () => {
      try {
        const result = await getWorkOrderStats();
        if (result.success && result.data) {
          setStatsData(result.data);

          // 공정별 카운트 → 탭 카운트에 반영
          const bp = result.data.byProcess;
          const counts: Record<string, number> = {
            [TAB_ALL]: result.data.total,
          };
          for (const [processId, count] of Object.entries(bp)) {
            counts[processId] = count;
          }
          setTabCounts(counts);
        }
      } 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 [tabCounts, setTabCounts] = useState<Record<string, number>>({});

  const tabs: TabOption[] = useMemo(
    () => [
      { value: TAB_ALL, label: '전체', count: tabCounts[TAB_ALL] },
      ...processList.map((p) => ({
        value: String(p.id),
        label: `${p.processName} 공정`,
        count: tabCounts[String(p.id)],
      })),
    ],
    [processList, tabCounts]
  );

  // ===== 통계 카드 6개 (기획서 기반) =====
  const stats: StatCard[] = useMemo(
    () => [
      {
        label: '전체 작업',
        value: statsData.total,
        icon: FileText,
        iconColor: 'text-gray-600',
      },
      {
        label: '작업 대기',
        value: statsData.waiting + statsData.unassigned + statsData.pending,
        icon: Clock,
        iconColor: 'text-yellow-600',
      },
      {
        label: '작업중',
        value: statsData.inProgress,
        icon: Loader,
        iconColor: 'text-blue-600',
      },
      {
        label: '작업 완료',
        value: statsData.completed,
        icon: CheckCircle2,
        iconColor: 'text-green-600',
      },
      {
        label: '긴급',
        value: 0, // TODO: API에서 긴급 건수 제공 시 연동
        icon: AlertTriangle,
        iconColor: 'text-red-600',
      },
      {
        label: '지연',
        value: 0, // TODO: API에서 지연 건수 제공 시 연동
        icon: TimerOff,
        iconColor: 'text-orange-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 tabValue = params?.tab || TAB_ALL;
            setActiveTab(tabValue);

            // 탭별 processId 결정
            // 'all' → 필터 없음 (전체), 'other' → 'none' (미지정), 그 외 → 공정 ID
            const processId = tabValue === TAB_ALL
              ? ('all' as const)
              : Number(tabValue);

            // 필터 값 추출
            const statusFilter = params?.filters?.status as string | undefined;
            const priorityFilter = params?.filters?.priority as string | undefined;

            const result = await getWorkOrders({
              page: params?.page || 1,
              perPage: params?.pageSize || ITEMS_PER_PAGE,
              processId,
              status: statusFilter && statusFilter !== 'all'
                ? (statusFilter as WorkOrderStatus)
                : undefined,
              priority: priorityFilter && priorityFilter !== 'all'
                ? priorityFilter
                : undefined,
              search: params?.search || undefined,
            });

            if (result.success) {
              // 통계 + 공정별 카운트 다시 로드
              const statsResult = await getWorkOrderStats();
              if (statsResult.success && statsResult.data) {
                setStatsData(statsResult.data);
                const bp = statsResult.data.byProcess;
                const counts: Record<string, number> = {
                  [TAB_ALL]: statsResult.data.total,
                };
                for (const [processId, count] of Object.entries(bp)) {
                  counts[processId] = count;
                }
                setTabCounts(counts);
              }

              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]', copyable: true },
        { key: 'salesOrderDate', label: '수주일', className: 'w-[100px]', copyable: true },
        { key: 'shipmentDate', label: '출고예정일', className: 'w-[110px]', copyable: true },
        { key: 'lotNo', label: '로트번호', className: 'min-w-[120px]', copyable: true },
        { key: 'client', label: '수주처', className: 'min-w-[120px]', copyable: true },
        { key: 'projectName', label: '현장명', className: 'min-w-[150px]', copyable: true },
        { key: 'shutterCount', label: '틀수', className: 'w-[70px] text-center', copyable: true },
        { key: 'category', label: '구분', className: 'w-[80px]', copyable: true },
        { key: 'status', label: '상태', className: 'w-[90px]' },
        { key: 'priority', label: '우선순위', className: 'w-[80px]' },
        { key: 'department', label: '부서', className: 'w-[90px]', copyable: true },
        { key: 'note', label: '비고', className: 'min-w-[120px]', copyable: true },
      ],

      // 서버 사이드 페이지네이션
      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
        );
      },

      // 필터 설정 (상태 + 우선순위)
      filterConfig,
      initialFilters: {
        status: 'all',
        priority: 'all',
      },

      // 탭 설정 (전체 + 공정 + 기타) — 통계 카드 위에 배치
      tabs,
      defaultTab: TAB_ALL,
      tabsPosition: 'above-stats',

      // 테이블 헤더 액션 (절곡 공정 탭일 때만 재공품 생산 버튼)
      tableHeaderActions: (() => {
        const bendingProcess = processList.find(p => p.processName === '절곡');
        return bendingProcess && activeTab === String(bendingProcess.id);
      })() ? (
        <Button
          onClick={() => setIsWipModalOpen(true)}
          className="bg-orange-500 hover:bg-orange-600 text-white"
          size="sm"
        >
          재공품 생산
        </Button>
      ) : undefined,

      // 통계 카드 (6개)
      stats,

      // 날짜 범위 선택기
      dateRangeSelector: {
        enabled: true,
        showPresets: true,
      },

      // 등록 버튼 (발주에서 넘어오는 형태로 변경 예정)
      // createButton: {
      //   label: '등록',
      //   onClick: handleCreate,
      // },

      // 테이블 행 렌더링
      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.salesOrderDate}</TableCell>
            <TableCell>{item.shipmentDate}</TableCell>
            <TableCell>{item.lotNo}</TableCell>
            <TableCell>{item.client}</TableCell>
            <TableCell className="max-w-[200px] truncate">{item.projectName}</TableCell>
            <TableCell className="text-center">{item.shutterCount ?? '-'}</TableCell>
            <TableCell>{item.processName !== '-' ? item.processName : '-'}</TableCell>
            <TableCell>
              <Badge className={`${WORK_ORDER_STATUS_COLORS[item.status]} border-0`}>
                {WORK_ORDER_STATUS_LABELS[item.status]}
              </Badge>
            </TableCell>
            <TableCell>
              <Badge className={`${getPriorityStyle(item.priorityLabel)} border-0`}>
                {item.priorityLabel}
              </Badge>
            </TableCell>
            <TableCell>{item.department && item.department !== '-' ? item.department : '-'}</TableCell>
            <TableCell className="max-w-[150px] truncate">{item.note || '-'}</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.client} />
                <InfoField label="로트번호" value={item.lotNo} />
                <InfoField label="수주일" value={item.salesOrderDate} />
                <InfoField label="출고예정일" value={item.shipmentDate} />
                <InfoField label="틀수" value={item.shutterCount ?? '-'} />
                <InfoField label="우선순위" value={item.priorityLabel} />
                <InfoField label="부서" value={item.department} />
                <InfoField label="비고" value={item.note || '-'} />
              </div>
            }
          />
        );
      },
    }),
    [tabs, stats, processList, handleRowClick, activeTab]
  );

  return (
    <>
      <UniversalListPage config={config} externalIsLoading={!processMapLoaded} />
      <WipProductionModal
        open={isWipModalOpen}
        onOpenChange={setIsWipModalOpen}
      />
    </>
  );
}
