'use client';

/**
 * 작업지시서 리스트 패널 (좌측)
 *
 * 마스터-디테일 레이아웃의 좌측 패널.
 * 공정별 필터링된 작업지시서 목록을 표시하고 선택 기능 제공.
 */

import { cn } from '@/lib/utils';
import { AlertTriangle, Package } from 'lucide-react';
import type { WorkOrder } from '../ProductionDashboard/types';

interface WorkOrderListPanelProps {
  workOrders: WorkOrder[];
  selectedId: string | null;
  onSelect: (id: string) => void;
  isLoading: boolean;
}

export function WorkOrderListPanel({
  workOrders,
  selectedId,
  onSelect,
  isLoading,
}: WorkOrderListPanelProps) {
  if (isLoading) {
    return (
      <div className="p-2 space-y-1.5">
        {Array.from({ length: 5 }).map((_, i) => (
          <div key={i} className="h-[84px] rounded-lg bg-gray-100 animate-pulse" />
        ))}
      </div>
    );
  }

  if (workOrders.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center h-full text-muted-foreground p-6">
        <Package className="h-10 w-10 mb-2 opacity-40" />
        <p className="text-sm">배정된 작업이 없습니다.</p>
      </div>
    );
  }

  return (
    <div className="overflow-y-auto h-full p-2 space-y-1.5">
      {workOrders.map((order, index) => (
        <button
          key={order.id}
          onClick={() => onSelect(order.id)}
          className={cn(
            'w-full text-left p-3 rounded-lg border transition-all duration-150',
            selectedId === order.id
              ? 'bg-primary/5 border-primary/30 shadow-sm'
              : 'bg-white border-gray-100 hover:bg-gray-50 hover:border-gray-200'
          )}
        >
          {/* 헤더: 번호 + 작업지시번호 + 상태 */}
          <div className="flex items-center justify-between mb-1">
            <div className="flex items-center gap-2 min-w-0">
              <span className="flex items-center justify-center w-6 h-6 rounded-full bg-emerald-500 text-white text-xs font-bold shrink-0">
                {index + 1}
              </span>
              <span className="text-sm font-semibold text-gray-900 truncate">
                {order.orderNo}
              </span>
            </div>
            <div className="flex items-center gap-1.5 shrink-0 ml-2">
              {order.isUrgent && (
                <AlertTriangle className="h-3.5 w-3.5 text-red-500" />
              )}
              <StatusBadge status={order.status} />
            </div>
          </div>

          {/* 제품코드 (제품명) */}
          <p className="text-sm text-gray-600 truncate ml-8">
            {order.productCode !== '-' ? order.productCode : order.productName}
          </p>

          {/* 현장명 + 수량 */}
          <div className="flex items-center justify-between mt-1.5 ml-8">
            <span className="text-xs text-gray-400 truncate">
              {order.projectName || order.client}
            </span>
            <span className="text-xs font-medium text-gray-500 shrink-0">
              {order.quantity}EA
            </span>
          </div>

          {/* 납기일 */}
          {order.dueDate && (
            <div className="mt-1 ml-8">
              <span
                className={cn(
                  'text-[11px]',
                  order.isDelayed
                    ? 'text-red-500 font-medium'
                    : 'text-gray-400'
                )}
              >
                납기: {new Date(order.dueDate).toLocaleDateString('ko-KR')}
                {order.isDelayed &&
                  order.delayDays &&
                  ` (${order.delayDays}일 지연)`}
              </span>
            </div>
          )}
        </button>
      ))}
    </div>
  );
}

function StatusBadge({ status }: { status: string }) {
  const config: Record<string, { label: string; className: string }> = {
    waiting: { label: '대기', className: 'bg-gray-100 text-gray-600' },
    inProgress: { label: '작업중', className: 'bg-blue-100 text-blue-700' },
    completed: { label: '완료', className: 'bg-green-100 text-green-700' },
  };
  const { label, className } = config[status] || config.waiting;
  return (
    <span
      className={cn(
        'text-[10px] font-medium px-1.5 py-0.5 rounded',
        className
      )}
    >
      {label}
    </span>
  );
}
