'use client';

/**
 * 작업 아이템 카드 컴포넌트 (기획서 기반)
 *
 * 디자인 스펙 (스크린샷 2026-02-05 기준):
 * - 카드: 흰색 배경, 미세한 그림자
 * - 헤더: 번호 뱃지(녹색 원) + 품목코드(품목명) + 층/부호(우측 정렬)
 * - 제작 사이즈: 한 줄로 표시
 * - 절단정보: 연한 회색 박스 (라벨 상단, 값 하단)
 * - 진행률: 파란색 프로그래스 바 + 우측에 "N/M 완료"
 * - 공정 버튼: 완료는 녹색 배경, 미완료는 다크 배경
 * - 자재 투입 목록: 토글 (쉐브론 아이콘 + 텍스트)
 */

import { useState, useCallback, memo } from 'react';
import { ChevronDown, ChevronUp, SquarePen, Trash2 } from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { cn } from '@/lib/utils';
import type {
  WorkItemData,
  WorkStepData,
  MaterialListItem,
} from './types';
import { formatNumber } from '@/lib/utils/amount';

interface WorkItemCardProps {
  item: WorkItemData;
  onStepClick: (itemId: string, step: WorkStepData) => void;
  onEditMaterial: (itemId: string, material: MaterialListItem) => void;
  onDeleteMaterial: (itemId: string, materialId: string) => void;
  onInspectionClick?: (itemId: string) => void;
  inspectionChecked?: boolean;
  onInspectionToggle?: (itemId: string, checked: boolean) => void;
}

export const WorkItemCard = memo(function WorkItemCard({
  item,
  onStepClick,
  onEditMaterial,
  onDeleteMaterial,
  onInspectionClick,
  inspectionChecked: _inspectionChecked,
  onInspectionToggle: _onInspectionToggle,
}: WorkItemCardProps) {
  const [isMaterialListOpen, setIsMaterialListOpen] = useState(false);

  // 진척률 계산
  const completedSteps = item.steps.filter((s) => s.isCompleted).length;
  const totalSteps = item.steps.length;
  const progressPercent = totalSteps > 0 ? (completedSteps / totalSteps) * 100 : 0;

  const handleStepClick = useCallback(
    (step: WorkStepData) => {
      onStepClick(item.id, step);
    },
    [item.id, onStepClick]
  );

  return (
    <Card className="bg-white shadow-sm border border-gray-100">
      <CardContent className="p-5 space-y-4">
        {/* 헤더: 번호 뱃지 + 품목코드(품목명) + 층/부호 */}
        <div className="flex items-start justify-between">
          <div className="flex items-center gap-3">
            <span className="flex items-center justify-center w-8 h-8 rounded-full bg-emerald-500 text-white text-sm font-bold shrink-0">
              {item.itemNo}
            </span>
            <div>
              <span className="text-base font-bold text-gray-900">
                {item.itemCode} - {item.itemName}
              </span>
              {item.bdCode && (
                <span className="ml-2 text-xs font-mono text-blue-600 bg-blue-50 px-1.5 py-0.5 rounded">
                  {item.bdCode}
                </span>
              )}
            </div>
          </div>
          {!item.isWip && (
            <span className="text-sm text-gray-500 shrink-0">
              {item.floor} / {item.code}
            </span>
          )}
        </div>

        {/* 제작 사이즈 (재공품은 숨김) */}
        {!item.isWip && (
          <div className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-sm text-gray-700">
            <span className="text-gray-500">제작 사이즈</span>
            <span className="font-medium">
              {formatNumber(item.width)} X {formatNumber(item.height)} mm
            </span>
            <span className="text-gray-500">수량</span>
            <span className="font-medium text-gray-900">{item.quantity}개</span>
          </div>
        )}

        {/* 공정별 추가 정보 */}
        {item.processType === 'screen' && item.cuttingInfo && (
          <ScreenCuttingInfo
            width={item.cuttingInfo.width}
            sheets={item.cuttingInfo.sheets}
          />
        )}

        {item.processType === 'slat' && item.slatInfo && (
          <SlatExtraInfo
            length={item.slatInfo.length}
            slatCount={item.slatInfo.slatCount}
            jointBar={item.slatInfo.jointBar}
          />
        )}

        {item.processType === 'bending' && !item.isWip && item.bendingInfo && (
          <BendingExtraInfo info={item.bendingInfo} />
        )}

        {item.isWip && item.wipInfo && (
          <WipExtraInfo info={item.wipInfo} />
        )}

        {/* 진척률 프로그래스 바 */}
        <div className="space-y-1.5">
          <div className="w-full h-2 bg-gray-100 rounded-full overflow-hidden">
            <div
              className="h-full bg-gradient-to-r from-blue-400 to-blue-500 rounded-full transition-all duration-300"
              style={{ width: `${progressPercent}%` }}
            />
          </div>
          <p className="text-sm text-gray-500 text-right">
            {completedSteps}/{totalSteps} 완료
          </p>
        </div>

        {/* 공정 단계 버튼 - 순차 진행 (이전 단계 완료 후 다음 단계 활성화) */}
        <div className="flex flex-wrap gap-2">
          {item.steps.map((step, idx) => {
            const prevCompleted = idx === 0 || item.steps[idx - 1].isCompleted;
            const isLocked = !step.isCompleted && !prevCompleted;
            return (
              <button
                key={step.id}
                disabled={isLocked}
                onClick={() => {
                  if (isLocked) return;
                  if (step.isInspection && onInspectionClick) {
                    onInspectionClick(item.id);
                  } else {
                    handleStepClick(step);
                  }
                }}
                className={cn(
                  'px-4 py-2 rounded-lg text-sm font-medium transition-colors',
                  step.isCompleted
                    ? 'bg-emerald-500 text-white hover:bg-emerald-600'
                    : isLocked
                      ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                      : 'bg-gray-800 text-white hover:bg-gray-700'
                )}
              >
                {step.name}
                {step.isCompleted && (
                  <span className="ml-1.5 font-semibold">완료</span>
                )}
              </button>
            );
          })}
        </div>

        {/* 자재 투입 목록 (토글) */}
        <div className="pt-1">
          <button
            onClick={() => setIsMaterialListOpen(!isMaterialListOpen)}
            className="flex items-center gap-1.5 text-sm font-medium text-gray-600 hover:text-gray-900 transition-colors"
          >
            {isMaterialListOpen ? (
              <ChevronUp className="h-4 w-4" />
            ) : (
              <ChevronDown className="h-4 w-4" />
            )}
            자재 투입 목록
          </button>

          {isMaterialListOpen && (
            <div className="mt-3 border rounded-lg overflow-hidden">
              {(!item.materialInputs || item.materialInputs.length === 0) ? (
                <div className="py-6 text-center text-sm text-gray-500">
                  투입된 자재가 없습니다.
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow className="bg-gray-50">
                      <TableHead className="text-center text-xs">로트번호</TableHead>
                      <TableHead className="text-center text-xs">품목명</TableHead>
                      <TableHead className="text-center text-xs">수량</TableHead>
                      <TableHead className="text-center text-xs">단위</TableHead>
                      <TableHead className="text-center text-xs">관리</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {item.materialInputs.map((mat) => (
                      <TableRow key={mat.id}>
                        <TableCell className="text-center text-xs">{mat.lotNo}</TableCell>
                        <TableCell className="text-center text-xs">{mat.itemName}</TableCell>
                        <TableCell className="text-center text-xs">{formatNumber(parseFloat(String(mat.quantity)))}</TableCell>
                        <TableCell className="text-center text-xs">{mat.unit}</TableCell>
                        <TableCell className="text-center">
                          <div className="flex items-center justify-center gap-1">
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-7 w-7 p-0"
                              onClick={() => onEditMaterial(item.id, mat)}
                            >
                              <SquarePen className="h-3.5 w-3.5 text-gray-500" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              className="h-7 w-7 p-0"
                              onClick={() => onDeleteMaterial(item.id, mat.id)}
                            >
                              <Trash2 className="h-3.5 w-3.5 text-red-500" />
                            </Button>
                          </div>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
});

// ===== 스크린 전용: 절단정보 =====
function ScreenCuttingInfo({ width, sheets }: { width: number; sheets: number }) {
  return (
    <div className="p-4 bg-gray-50 rounded-lg border border-gray-100">
      <p className="text-xs text-gray-400 mb-1.5">절단정보</p>
      <p className="text-base font-semibold text-gray-900">
        폭 {formatNumber(width)}mm X {sheets}장
      </p>
    </div>
  );
}

// ===== 슬랫 전용: 길이/매수/조인트바 =====
function SlatExtraInfo({
  length,
  slatCount,
  jointBar,
}: {
  length?: number;
  slatCount?: number;
  jointBar?: number;
}) {
  return (
    <div className="flex flex-wrap gap-2">
      {length != null && length > 0 && (
        <Badge variant="outline" className="text-xs px-2.5 py-1 border-gray-300">
          길이 {formatNumber(length)}mm
        </Badge>
      )}
      {slatCount != null && slatCount > 0 && (
        <Badge variant="outline" className="text-xs px-2.5 py-1 border-gray-300">
          슬랫 매수 {slatCount}장
        </Badge>
      )}
      {jointBar != null && jointBar > 0 && (
        <Badge variant="outline" className="text-xs px-2.5 py-1 border-gray-300">
          조인트바 {jointBar}개
        </Badge>
      )}
    </div>
  );
}

// ===== 절곡 전용: 도면 + 공통사항 + 세부부품 =====
import type { BendingInfo, WipInfo } from './types';

function BendingExtraInfo({ info }: { info: BendingInfo }) {
  return (
    <div className="space-y-3">
      {/* 공통사항 */}
      <div>
        <p className="text-xs font-medium text-gray-500">공통사항</p>
        <div className="space-y-1 mt-1.5">
          <div className="flex gap-2 text-xs">
            <span className="text-gray-500 w-14">종류</span>
            <span className="text-gray-900 font-medium">{info.common.kind}</span>
          </div>
          <div className="flex gap-2 text-xs">
            <span className="text-gray-500 w-14">유형</span>
            <span className="text-gray-900 font-medium">{info.common.type}</span>
          </div>
          {info.common.lengthQuantities.map((lq, i) => (
            <div key={i} className="flex gap-2 text-xs">
              <span className="text-gray-500 w-14">{i === 0 ? '길이별 수량' : ''}</span>
              <span className="text-gray-900 font-medium">
                {formatNumber(lq.length)}mm X {lq.quantity}개
              </span>
            </div>
          ))}
        </div>
      </div>

      {/* 세부부품 */}
      {info.detailParts.length > 0 && (
        <div>
          <p className="text-xs font-medium text-gray-500 mb-1.5">
            세부부품 ({info.detailParts.length}개)
          </p>
          <div className="border rounded-lg divide-y divide-gray-100">
            {info.detailParts.map((part, i) => (
              <div key={i} className="p-2.5 space-y-1">
                <div className="flex items-center justify-between text-xs">
                  <span className="font-medium text-gray-900">{part.partName}</span>
                  <span className="text-gray-500">{part.material}</span>
                </div>
                <p className="text-xs text-gray-600">
                  바아시 정보 {part.barcyInfo}
                </p>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ===== 재공품 전용: 도면 + 공통사항 (규격, 길이별 수량) =====
function WipExtraInfo({ info }: { info: WipInfo }) {
  return (
    <div>
      <p className="text-xs font-medium text-gray-500 mb-2">공통사항</p>
      <div className="border rounded-lg divide-y">
        <div className="flex">
          <span className="px-3 py-2.5 text-xs text-gray-500 bg-gray-50 w-20 flex-shrink-0 border-r">규격</span>
          <span className="px-3 py-2.5 text-xs font-semibold text-gray-900 flex-1 text-right">{info.specification}</span>
        </div>
        <div className="flex">
          <span className="px-3 py-2.5 text-xs text-gray-500 bg-gray-50 w-20 flex-shrink-0 border-r">길이별 수량</span>
          <span className="px-3 py-2.5 text-xs font-semibold text-gray-900 flex-1 text-right">{info.lengthQuantity}</span>
        </div>
      </div>
    </div>
  );
}
