'use client';

/**
 * 공정상세 섹션 컴포넌트
 *
 * WorkCard 내부에서 토글 확장되는 공정 상세 정보
 * - 자재 투입 필요 섹션
 * - 공정 단계 (5단계)
 * - 각 단계별 세부 항목
 */

import { useState } from 'react';
import { Package, CheckCircle2, Circle, AlertTriangle, MapPin, Ruler } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { cn } from '@/lib/utils';
import type { ProcessStep, ProcessStepItem } from './types';

// Mock 공정 단계 데이터
const MOCK_PROCESS_STEPS: ProcessStep[] = [
  {
    id: 'step-1',
    stepNo: 1,
    name: '절곡판/코일 절단',
    completed: 0,
    total: 2,
    items: [
      {
        id: 'item-1-1',
        itemNo: '#1',
        location: '1층 1호-A',
        isPriority: true,
        spec: 'W2500 × H3000',
        material: '절곡판',
        lot: 'LOT-절곡-2025-001',
      },
      {
        id: 'item-1-2',
        itemNo: '#2',
        location: '1층 1호-B',
        isPriority: false,
        spec: 'W2000 × H2500',
        material: '절곡판',
        lot: 'LOT-절곡-2025-002',
      },
    ],
  },
  {
    id: 'step-2',
    stepNo: 2,
    name: 'V컷팅',
    completed: 0,
    total: 2,
    items: [
      {
        id: 'item-2-1',
        itemNo: '#1',
        location: '1층 2호-A',
        isPriority: false,
        spec: 'V10 × L2500',
        material: 'V컷팅재',
        lot: 'LOT-V컷-2025-001',
      },
    ],
  },
  {
    id: 'step-3',
    stepNo: 3,
    name: '절곡',
    completed: 0,
    total: 3,
    items: [
      {
        id: 'item-3-1',
        itemNo: '#1',
        location: '2층 1호',
        isPriority: true,
        spec: '90° × 2회',
        material: '절곡판',
        lot: 'LOT-절곡-2025-001',
      },
    ],
  },
  {
    id: 'step-4',
    stepNo: 4,
    name: '중간검사',
    isInspection: true,
    completed: 0,
    total: 1,
    items: [],
  },
  {
    id: 'step-5',
    stepNo: 5,
    name: '포장',
    completed: 0,
    total: 1,
    items: [],
  },
];

interface ProcessDetailSectionProps {
  isExpanded: boolean;
  materialRequired: boolean;
  onMaterialInput: () => void;
}

export function ProcessDetailSection({
  isExpanded,
  materialRequired,
  onMaterialInput,
}: ProcessDetailSectionProps) {
  const [steps] = useState<ProcessStep[]>(MOCK_PROCESS_STEPS);
  const [expandedSteps, setExpandedSteps] = useState<Set<string>>(new Set());

  const totalSteps = steps.length;
  const completedSteps = steps.filter((s) => s.completed === s.total).length;

  const toggleStep = (stepId: string) => {
    setExpandedSteps((prev) => {
      const next = new Set(prev);
      if (next.has(stepId)) {
        next.delete(stepId);
      } else {
        next.add(stepId);
      }
      return next;
    });
  };

  if (!isExpanded) return null;

  return (
    <div className="mt-4 pt-4 border-t space-y-4">
      {/* 자재 투입 필요 섹션 */}
      {materialRequired && (
        <div className="bg-orange-50 border border-orange-200 rounded-lg p-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <AlertTriangle className="h-4 w-4 text-orange-500" />
              <span className="text-sm font-medium text-orange-800">
                자재 투입이 필요합니다
              </span>
            </div>
            <Button
              size="sm"
              variant="outline"
              onClick={onMaterialInput}
              className="border-orange-300 text-orange-700 hover:bg-orange-100"
            >
              <Package className="mr-1 h-4 w-4" />
              자재 투입하기
            </Button>
          </div>
        </div>
      )}

      {/* 공정 단계 헤더 */}
      <div className="flex items-center justify-between">
        <h4 className="text-sm font-medium">공정 단계</h4>
        <Badge variant="outline" className="text-xs">
          {completedSteps}/{totalSteps} 완료
        </Badge>
      </div>

      {/* 공정 단계 목록 */}
      <div className="space-y-2">
        {steps.map((step) => (
          <ProcessStepCard
            key={step.id}
            step={step}
            isExpanded={expandedSteps.has(step.id)}
            onToggle={() => toggleStep(step.id)}
          />
        ))}
      </div>
    </div>
  );
}

// ===== 하위 컴포넌트 =====

interface ProcessStepCardProps {
  step: ProcessStep;
  isExpanded: boolean;
  onToggle: () => void;
}

function ProcessStepCard({ step, isExpanded, onToggle }: ProcessStepCardProps) {
  const isCompleted = step.completed === step.total;
  const hasItems = step.items.length > 0;

  return (
    <Collapsible open={isExpanded} onOpenChange={onToggle}>
      <CollapsibleTrigger asChild>
        <div
          className={cn(
            'flex items-center justify-between p-3 rounded-lg border cursor-pointer transition-colors',
            isCompleted
              ? 'bg-green-50 border-green-200'
              : 'bg-gray-50 border-gray-200 hover:bg-gray-100'
          )}
        >
          <div className="flex items-center gap-3">
            {isCompleted ? (
              <CheckCircle2 className="h-5 w-5 text-green-500" />
            ) : (
              <Circle className="h-5 w-5 text-gray-400" />
            )}
            <div>
              <div className="flex items-center gap-2">
                <span className="text-sm font-medium">
                  {step.stepNo}. {step.name}
                </span>
                {step.isInspection && (
                  <Badge variant="secondary" className="text-xs">
                    검사
                  </Badge>
                )}
              </div>
              <span className="text-xs text-muted-foreground">
                {step.completed}/{step.total} 완료
              </span>
            </div>
          </div>
          {hasItems && (
            <span className="text-xs text-muted-foreground">
              {isExpanded ? '접기' : '펼치기'}
            </span>
          )}
        </div>
      </CollapsibleTrigger>

      {hasItems && (
        <CollapsibleContent>
          <div className="ml-8 mt-2 space-y-2">
            {step.items.map((item) => (
              <ProcessStepItemCard key={item.id} item={item} />
            ))}
          </div>
        </CollapsibleContent>
      )}
    </Collapsible>
  );
}

interface ProcessStepItemCardProps {
  item: ProcessStepItem;
}

function ProcessStepItemCard({ item }: ProcessStepItemCardProps) {
  return (
    <div className="p-3 bg-white border rounded-lg text-sm">
      <div className="flex items-center justify-between mb-2">
        <div className="flex items-center gap-2">
          <span className="font-medium">{item.itemNo}</span>
          {item.isPriority && (
            <Badge variant="destructive" className="text-xs">
              선행 생산
            </Badge>
          )}
        </div>
        <Badge variant="outline" className="text-xs font-mono">
          {item.lot}
        </Badge>
      </div>
      <div className="grid grid-cols-2 gap-2 text-xs text-muted-foreground">
        <div className="flex items-center gap-1">
          <MapPin className="h-3 w-3" />
          <span>{item.location}</span>
        </div>
        <div className="flex items-center gap-1">
          <Ruler className="h-3 w-3" />
          <span>{item.spec}</span>
        </div>
        <div className="col-span-2 flex items-center gap-1">
          <Package className="h-3 w-3" />
          <span>자재: {item.material}</span>
        </div>
      </div>
    </div>
  );
}