'use client';

/**
 * 셔터박스 섹션
 *
 * 방향별(양면/밑면/후면) 구성요소 + SVG 다이어그램
 * PHP에서는 GD로 동적 이미지 생성 → React에서는 source 이미지 + 치수 텍스트 오버레이
 */

import type { BendingInfoExtended, ShutterBoxData } from './types';
import { buildShutterBoxRows, getBendingImageUrl, fmt, fmtWeight, lookupLotNo } from './utils';

interface ShutterBoxSectionProps {
  bendingInfo: BendingInfoExtended;
  lotNoMap?: Record<string, string>;
  bendingImages?: Record<string, string>;
}

function ShutterBoxSubSection({ box, index, lotNoMap, bendingImages }: { box: ShutterBoxData; index: number; lotNoMap?: Record<string, string>; bendingImages?: Record<string, string> }) {
  const rows = buildShutterBoxRows(box);
  if (rows.length === 0) return null;

  const directionMap: Record<string, 'both' | 'bottom' | 'rear'> = {
    '양면': 'both',
    '밑면': 'bottom',
    '후면': 'rear',
  };
  const imageType = directionMap[box.direction] || 'both';

  return (
    <div className="mb-4">
      <div className="text-xs font-bold mb-1">
        3.{index + 1} 셔터박스 [{box.size}] {box.direction}
      </div>

      <div className="flex gap-3">
        {/* 좌측: 이미지 (source 이미지에 치수 오버레이) */}
        <div className="flex-shrink-0 w-48">
          <div className="relative">
            <img
              src={getBendingImageUrl('box', '', imageType, bendingImages)}
              alt={`셔터박스 ${box.direction}`}
              className="w-full border border-gray-300"
            />
            {/* 치수 텍스트 오버레이 */}
            <div className="absolute bottom-1 left-1 text-xs bg-white/80 px-1 rounded">
              {box.size} ({box.direction})
            </div>
          </div>
          <div className="text-xs text-gray-500 mt-1">
            레일폭: {box.railWidth}mm
          </div>
        </div>

        {/* 우측: 테이블 */}
        <div className="flex-1">
          <table className="w-full border-collapse text-xs">
            <thead>
              <tr className="bg-gray-100">
                <th className="border border-gray-400 px-1 py-0.5">구성요소</th>
                <th className="border border-gray-400 px-1 py-0.5">재질</th>
                <th className="border border-gray-400 px-1 py-0.5">길이/치수</th>
                <th className="border border-gray-400 px-1 py-0.5">수량</th>
                <th className="border border-gray-400 px-1 py-0.5">LOT NO</th>
                <th className="border border-gray-400 px-1 py-0.5">무게(kg)</th>
              </tr>
            </thead>
            <tbody>
              {rows.map((row, idx) => (
                <tr key={idx}>
                  <td className="border border-gray-400 px-1 py-0.5">{row.partName}</td>
                  <td className="border border-gray-400 px-1 py-0.5 text-center">{row.material}</td>
                  <td className="border border-gray-400 px-1 py-0.5 text-center">{row.dimension}</td>
                  <td className="border border-gray-400 px-1 py-0.5 text-center">{fmt(row.quantity)}</td>
                  <td className="border border-gray-400 px-1 py-0.5 text-center">
                    {(() => {
                      const dimNum = parseInt(row.dimension);
                      if (!isNaN(dimNum) && !row.dimension.includes('*')) {
                        return lookupLotNo(lotNoMap, row.lotPrefix, dimNum);
                      }
                      // 치수형(1219*539 등)도 prefix-only fallback
                      return lookupLotNo(lotNoMap, row.lotPrefix);
                    })()}
                  </td>
                  <td className="border border-gray-400 px-1 py-0.5 text-center">{fmtWeight(row.weight)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

export function ShutterBoxSection({ bendingInfo, lotNoMap, bendingImages }: ShutterBoxSectionProps) {
  const boxes = bendingInfo.shutterBox;
  if (!boxes || boxes.length === 0) return null;

  return (
    <div className="mb-6">
      <div className="bg-gray-800 text-white text-xs font-bold px-3 py-1.5 mb-2">
        3. 셔터박스
      </div>

      {boxes.map((box, idx) => (
        <ShutterBoxSubSection key={idx} box={box} index={idx} lotNoMap={lotNoMap} bendingImages={bendingImages} />
      ))}
    </div>
  );
}
