'use client';

/**
 * 작업 카드 컴포넌트
 *
 * 기획 화면에 맞춘 레이아웃:
 * - 헤더 박스: 품목명 + 수량
 * - 뱃지 영역: 순위/긴급/상태(좌측), 납기(우측)
 * - 공정 + 작업번호
 * - 업체/현장
 * - 담당자
 * - 지시 박스 (회색 배경)
 * - 전량완료 버튼 (검은색, 전체너비)
 * - 4버튼 2x2 그리드
 */

import { useState } from 'react';
import { ChevronDown } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { getPresetStyle } from '@/lib/utils/status-config';
import { Button } from '@/components/ui/button';
import type { WorkOrder } from '../ProductionDashboard/types';
import { 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);

  // 납기일 포맷 (YYYY-MM-DD)
  const formatDueDate = (dateStr: string) => {
    const date = new Date(dateStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  return (
    <Card className="bg-white shadow-sm border border-gray-200">
      <CardContent className="p-0">
        {/* 헤더 박스: 품목명 + 수량 */}
        <div className="flex items-center justify-between p-4 border-b border-gray-100">
          <h3 className="text-lg font-semibold text-gray-900">
            {order.productCode !== '-' ? order.productCode : order.productName}
          </h3>
          <div className="text-right">
            <span className="text-2xl font-bold text-gray-900">{order.quantity}</span>
            <span className="text-sm text-gray-500 ml-1">EA</span>
          </div>
        </div>

        {/* 본문 영역 */}
        <div className="p-4 space-y-3">
          {/* 뱃지 영역: 순위/긴급/상태(좌측), 납기(우측) */}
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              {/* 순위 뱃지 */}
              {order.priority <= 3 && (
                <Badge className={`${getPresetStyle('success')} text-xs font-medium px-2.5 py-1 rounded`}>
                  {order.priority}순위
                </Badge>
              )}
              {/* 긴급 뱃지 */}
              {order.isUrgent && (
                <Badge className={`${getPresetStyle('destructive')} text-xs font-medium px-2.5 py-1 rounded`}>
                  긴급
                </Badge>
              )}
              {/* 상태 뱃지 */}
              <Badge
                variant="secondary"
                className="bg-gray-200 hover:bg-gray-200 text-gray-700 text-xs font-medium px-2.5 py-1 rounded"
              >
                {STATUS_LABELS[order.status]}
              </Badge>
            </div>
            {/* 납기 */}
            <div className="text-right">
              <p className="text-xs text-gray-500">납기</p>
              <p className="text-sm font-semibold text-gray-900">{formatDueDate(order.dueDate)}</p>
            </div>
          </div>

          {/* 공정 뱃지 + 작업번호 */}
          <div className="flex items-center gap-2">
            <Badge
              variant="outline"
              className="text-xs font-medium px-2.5 py-1 border-gray-300 text-gray-600 rounded"
            >
              {order.processName}
            </Badge>
            <span className="text-sm text-gray-700">{order.orderNo}</span>
          </div>

          {/* 업체/현장 */}
          <p className="text-sm text-gray-600">
            {order.client} · {order.projectName}
          </p>

          {/* 담당자 */}
          {order.assignees && order.assignees.length > 0 && (
            <p className="text-sm text-gray-600">
              담당: {order.assignees.join(', ')}
            </p>
          )}

          {/* 지시 박스 (회색 배경) */}
          {order.instruction && (
            <div className="p-3 bg-gray-100 rounded-lg">
              <p className="text-sm text-gray-700">
                <span className="font-medium">지시:</span> {order.instruction}
              </p>
            </div>
          )}

          {/* 전량완료 버튼 - 검은색, 전체 너비 */}
          <Button
            onClick={() => onComplete(order)}
            className="w-full bg-gray-900 hover:bg-gray-800 text-white font-medium py-3 rounded-lg"
          >
            전량완료
          </Button>

          {/* 4버튼 2x2 그리드 */}
          <div className="grid grid-cols-2 gap-2">
            <Button
              variant="outline"
              onClick={() => {
                setIsExpanded(!isExpanded);
                onProcessDetail(order);
              }}
              className="w-full border-gray-300 text-gray-700 font-medium py-3 rounded-lg hover:bg-gray-50"
            >
              공정상세
              <ChevronDown className={`ml-1 h-4 w-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`} />
            </Button>
            <Button
              variant="outline"
              onClick={() => onMaterialInput(order)}
              className="w-full border-gray-300 text-gray-700 font-medium py-3 rounded-lg hover:bg-gray-50"
            >
              자재투입
            </Button>
            <Button
              variant="outline"
              onClick={() => onWorkLog(order)}
              className="w-full border-gray-300 text-gray-700 font-medium py-3 rounded-lg hover:bg-gray-50"
            >
              작업일지
            </Button>
            <Button
              variant="outline"
              onClick={() => onIssueReport(order)}
              className="w-full border-gray-300 text-gray-700 font-medium py-3 rounded-lg hover:bg-gray-50"
            >
              이슈보고
            </Button>
          </div>

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