'use client';

/**
 * 작업지시 목록 페이지
 * IntegratedListTemplateV2 패턴 적용
 */

import { useState, 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 {
  IntegratedListTemplateV2,
  TabOption,
  TableColumn,
  StatCard,
} from '@/components/templates/IntegratedListTemplateV2';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import { mockWorkOrders, mockStats } from './mockData';
import {
  PROCESS_TYPE_LABELS,
  WORK_ORDER_STATUS_LABELS,
  WORK_ORDER_STATUS_COLORS,
  type WorkOrder,
} from './types';

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

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

export function WorkOrderList() {
  const router = useRouter();
  const [searchTerm, setSearchTerm] = useState('');
  const [activeTab, setActiveTab] = useState<TabFilter>('all');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);

  // 탭별 카운트 계산
  const tabCounts = useMemo(() => {
    return {
      all: mockWorkOrders.length,
      unassigned: mockWorkOrders.filter((o) => o.status === 'unassigned').length,
      pending: mockWorkOrders.filter((o) => o.status === 'pending').length,
      waiting: mockWorkOrders.filter((o) => o.status === 'waiting').length,
      in_progress: mockWorkOrders.filter((o) => o.status === 'in_progress').length,
      completed: mockWorkOrders.filter((o) => o.status === 'completed' || o.status === 'shipped').length,
    };
  }, []);

  // 탭 옵션
  const tabs: TabOption[] = [
    { value: 'all', label: '전체', count: tabCounts.all },
    { value: 'unassigned', label: '미배정', count: tabCounts.unassigned, color: 'gray' },
    { value: 'pending', label: '승인대기', count: tabCounts.pending, color: 'orange' },
    { value: 'waiting', label: '작업대기', count: tabCounts.waiting, color: 'yellow' },
    { value: 'in_progress', label: '작업중', count: tabCounts.in_progress, color: 'blue' },
    { value: 'completed', label: '작업완료', count: tabCounts.completed, color: 'green' },
  ];

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

  // 테이블 컬럼
  const tableColumns: TableColumn[] = [
    { 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]' },
  ];

  // 필터링된 데이터
  const filteredOrders = useMemo(() => {
    let result = [...mockWorkOrders];

    // 탭 필터
    if (activeTab !== 'all') {
      if (activeTab === 'completed') {
        result = result.filter((o) => o.status === 'completed' || o.status === 'shipped');
      } else {
        result = result.filter((o) => o.status === activeTab);
      }
    }

    // 검색 필터
    if (searchTerm) {
      const term = searchTerm.toLowerCase();
      result = result.filter(
        (o) =>
          o.workOrderNo.toLowerCase().includes(term) ||
          o.client.toLowerCase().includes(term) ||
          o.projectName.toLowerCase().includes(term)
      );
    }

    return result;
  }, [activeTab, searchTerm]);

  // 페이지네이션 데이터
  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    return filteredOrders.slice(startIndex, startIndex + ITEMS_PER_PAGE);
  }, [filteredOrders, currentPage]);

  // 페이지네이션 설정
  const pagination = {
    currentPage,
    totalPages: Math.ceil(filteredOrders.length / ITEMS_PER_PAGE),
    totalItems: filteredOrders.length,
    itemsPerPage: ITEMS_PER_PAGE,
    onPageChange: setCurrentPage,
  };

  // 선택 핸들러
  const handleToggleSelection = useCallback((id: string) => {
    setSelectedItems((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  }, []);

  const handleToggleSelectAll = useCallback(() => {
    if (selectedItems.size === paginatedData.length) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(paginatedData.map((o) => o.id)));
    }
  }, [paginatedData, selectedItems.size]);

  // 상세 페이지 이동
  const handleView = useCallback((id: string) => {
    router.push(`/production/work-orders/${id}`);
  }, [router]);

  // 등록 페이지 이동
  const handleCreate = () => {
    router.push('/production/work-orders/create');
  };

  // 탭 변경 시 페이지 리셋
  const handleTabChange = (value: string) => {
    setActiveTab(value as TabFilter);
    setCurrentPage(1);
    setSelectedItems(new Set());
  };

  // 검색 변경 시 페이지 리셋
  const handleSearchChange = (value: string) => {
    setSearchTerm(value);
    setCurrentPage(1);
  };

  // 테이블 행 렌더링
  const renderTableRow = (order: WorkOrder, index: number, globalIndex: number) => {
    const isSelected = selectedItems.has(order.id);

    return (
      <TableRow
        key={order.id}
        className={`cursor-pointer hover:bg-muted/50 ${isSelected ? 'bg-blue-50' : ''}`}
        onClick={() => handleView(order.id)}
      >
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox
            checked={isSelected}
            onCheckedChange={() => handleToggleSelection(order.id)}
          />
        </TableCell>
        <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
        <TableCell className="font-medium">{order.workOrderNo}</TableCell>
        <TableCell>{PROCESS_TYPE_LABELS[order.processType]}</TableCell>
        <TableCell>{order.lotNo}</TableCell>
        <TableCell>{order.orderDate}</TableCell>
        <TableCell className="text-center">{order.isAssigned ? 'Y' : '-'}</TableCell>
        <TableCell className="text-center">
          {order.status !== 'unassigned' && order.status !== 'pending' ? 'Y' : '-'}
        </TableCell>
        <TableCell className="text-center">{order.isStarted ? 'Y' : '-'}</TableCell>
        <TableCell>
          <Badge className={`${WORK_ORDER_STATUS_COLORS[order.status]} border-0`}>
            {WORK_ORDER_STATUS_LABELS[order.status]}
          </Badge>
        </TableCell>
        <TableCell className="text-center">{order.priority}</TableCell>
        <TableCell>{order.assignee}</TableCell>
        <TableCell className="max-w-[200px] truncate">{order.projectName}</TableCell>
        <TableCell>{order.shipmentDate}</TableCell>
      </TableRow>
    );
  };

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

  // 헤더 액션
  const headerActions = (
    <Button className="ml-auto" onClick={handleCreate}>
      <Plus className="w-4 h-4 mr-1.5" />
      등록
    </Button>
  );

  return (
    <IntegratedListTemplateV2<WorkOrder>
      title="작업지시 목록"
      description="생산 작업지시 관리"
      icon={FileText}
      headerActions={headerActions}
      stats={stats}
      searchValue={searchTerm}
      onSearchChange={handleSearchChange}
      searchPlaceholder="작업지시번호, 발주처, 현장명 검색..."
      tabs={tabs}
      activeTab={activeTab}
      onTabChange={handleTabChange}
      tableColumns={tableColumns}
      data={paginatedData}
      totalCount={filteredOrders.length}
      allData={filteredOrders}
      selectedItems={selectedItems}
      onToggleSelection={handleToggleSelection}
      onToggleSelectAll={handleToggleSelectAll}
      getItemId={(order) => order.id}
      renderTableRow={renderTableRow}
      renderMobileCard={renderMobileCard}
      pagination={pagination}
    />
  );
}