'use client';

/**
 * 작업 카드 컴포넌트
 *
 * 각 작업 항목을 카드 형태로 표시
 * 버튼: 전량완료, 공정상세, 자재투입, 작업일지, 이슈보고
 * 공정상세 토글 시 ProcessDetailSection 표시
 */

import { useState } from 'react';
import { CheckCircle, Layers, Package, FileText, AlertTriangle, ChevronDown } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import type { WorkOrder } from '../ProductionDashboard/types';
import { PROCESS_LABELS, STATUS_LABELS } from '../ProductionDashboard/types';
import { ProcessDetailSection } from './ProcessDetailSection';

interface WorkCardProps {
  order: WorkOrder;
  onComplete: (order: WorkOrder) => void;
  onProcessDetail: (order: WorkOrder) => void;
  onMaterialInput: (order: WorkOrder) => void;
  onWorkLog: (order: WorkOrder) => void;
  onIssueReport: (order: WorkOrder) => void;
}

export function WorkCard({
  order,
  onComplete,
  onProcessDetail,
  onMaterialInput,
  onWorkLog,
  onIssueReport,
}: WorkCardProps) {
  const [isExpanded, setIsExpanded] = useState(false);

  // 상태별 배지 스타일
  const statusBadgeStyle = {
    waiting: 'bg-gray-100 text-gray-700 border-gray-200',
    inProgress: 'bg-blue-100 text-blue-700 border-blue-200',
    completed: 'bg-green-100 text-green-700 border-green-200',
  };

  // 납기일 포맷 (YYYY. M. D.)
  const formatDueDate = (dateStr: string) => {
    const date = new Date(dateStr);
    return `${date.getFullYear()}. ${date.getMonth() + 1}. ${date.getDate()}.`;
  };

  return (
    <Card className={`${order.isUrgent ? 'border-red-200 bg-red-50/30' : 'bg-gray-50/50'} shadow-sm`}>
      <CardContent className="p-5">
        {/* 상단: 작업번호 + 상태 + 순위 */}
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-2">
            <span className="text-base font-semibold text-gray-900">
              {order.orderNo}
            </span>
            <Badge
              variant="outline"
              className={`text-xs font-medium rounded-full px-3 py-0.5 ${statusBadgeStyle[order.status]}`}
            >
              {STATUS_LABELS[order.status]}
            </Badge>
          </div>
          {order.priority <= 3 && (
            <Badge
              variant="outline"
              className="text-sm font-semibold rounded-full px-3 py-1 border-red-400 text-red-500 bg-white"
            >
              순위 {order.priority}
            </Badge>
          )}
        </div>

        {/* 제품명 + 수량 */}
        <div className="flex items-start justify-between mb-1">
          <div className="flex-1 space-y-0.5">
            <h3 className="font-semibold text-lg text-gray-900">{order.productName}</h3>
            <p className="text-sm text-gray-500">{order.client}</p>
            <p className="text-sm text-gray-500">{order.projectName}</p>
          </div>
          <div className="text-right pl-4">
            <p className="text-3xl font-bold text-gray-900">{order.quantity}</p>
            <p className="text-sm text-gray-500">EA</p>
          </div>
        </div>

        {/* 공정 + 납기 */}
        <div className="flex items-center gap-3 mt-4 mb-4">
          <Badge
            variant="outline"
            className="text-sm font-medium rounded-full px-3 py-1 bg-white border-gray-300 text-gray-700"
          >
            {PROCESS_LABELS[order.process]}
          </Badge>
          <span className="text-sm text-gray-500">
            납기: {formatDueDate(order.dueDate)}
          </span>
          {order.isDelayed && order.delayDays && (
            <span className="text-sm text-orange-600 font-medium">
              +{order.delayDays}일 지연
            </span>
          )}
        </div>

        {/* 지시사항 */}
        {order.instruction && (
          <div className="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg text-sm text-yellow-800">
            {order.instruction}
          </div>
        )}

        {/* 버튼 영역 - 첫 번째 줄 */}
        <div className="flex flex-wrap gap-2">
          <Button
            size="sm"
            onClick={() => onComplete(order)}
            className="bg-green-500 hover:bg-green-600 text-white rounded-full px-4 h-9"
          >
            <CheckCircle className="mr-1.5 h-4 w-4" />
            전량완료
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={() => {
              setIsExpanded(!isExpanded);
              onProcessDetail(order);
            }}
            className="rounded-full px-4 h-9 border-gray-300"
          >
            <Layers className="mr-1.5 h-4 w-4" />
            공정상세
            <ChevronDown className={`ml-1 h-4 w-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={() => onMaterialInput(order)}
            className="rounded-full px-4 h-9 border-gray-300"
          >
            <Package className="mr-1.5 h-4 w-4" />
            자재투입
          </Button>
          <Button
            size="sm"
            variant="outline"
            onClick={() => onWorkLog(order)}
            className="rounded-full px-4 h-9 border-gray-300"
          >
            <FileText className="mr-1.5 h-4 w-4" />
            작업일지
          </Button>
        </div>

        {/* 버튼 영역 - 두 번째 줄 (이슈보고) */}
        <div className="mt-2">
          <Button
            size="sm"
            variant="outline"
            onClick={() => onIssueReport(order)}
            className="rounded-full px-4 h-9 border-orange-300 text-orange-500 hover:bg-orange-50 hover:text-orange-600"
          >
            <AlertTriangle className="mr-1.5 h-4 w-4" />
            이슈보고
          </Button>
        </div>

        {/* 공정상세 섹션 (토글) */}
        <ProcessDetailSection
          isExpanded={isExpanded}
          materialRequired={true}
          onMaterialInput={() => onMaterialInput(order)}
        />
      </CardContent>
    </Card>
  );
}
