'use client';

/**
 * 가이드레일 섹션
 *
 * 1.1 벽면형 [130*75]: 이미지 + 세부품명/재질/길이/수량/LOT NO/무게 테이블
 * 1.2 측면형 [130*125]: 동일 구조
 */

import type { BendingInfoExtended, MaterialMapping, GuideRailPartRow } from './types';
import { buildWallGuideRailRows, buildSideGuideRailRows, getBendingImageUrl, fmt, fmtWeight, lookupLotNo } from './utils';

interface GuideRailSectionProps {
  bendingInfo: BendingInfoExtended;
  mapping: MaterialMapping;
  lotNo: string;
  lotNoMap?: Record<string, string>;
  bendingImages?: Record<string, string>;
}

function PartTable({ title, rows, imageUrl, lotNo: _lotNo, baseSize, lotNoMap }: {
  title: string;
  rows: GuideRailPartRow[];
  imageUrl: string;
  lotNo: string;
  baseSize?: string;
  lotNoMap?: Record<string, string>;
}) {
  if (rows.length === 0) return null;

  return (
    <div className="mb-4">
      <div className="text-xs font-bold mb-1">{title}</div>
      <div className="flex gap-3">
        {/* 좌측: 이미지 + LOT */}
        <div className="flex-shrink-0 w-48">
          <img src={imageUrl} alt={title} className="w-full border border-gray-300" />
          <div className="text-xs text-gray-500 mt-1">
            입고&amp;생산 LOT NO:<br />
            <span className="text-gray-400">_______________</span>
          </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.partName === '하부BASE' ? (baseSize || '-') : fmt(row.length)}
                  </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">
                    {lookupLotNo(lotNoMap, row.lotPrefix, row.length)}
                  </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 GuideRailSection({ bendingInfo, mapping, lotNo, lotNoMap, bendingImages }: GuideRailSectionProps) {
  const guideRail = bendingInfo.guideRail;
  if (!guideRail) return null;
  const { wall, side } = guideRail;
  const productCode = bendingInfo.productCode;
  const stockFilter = bendingInfo.stockPartFilter;

  let wallRows = wall
    ? buildWallGuideRailRows(wall.lengthData, wall.baseDimension || '135*80', mapping, productCode)
    : [];

  let sideRows = side
    ? buildSideGuideRailRows(side.lengthData, side.baseDimension || '135*130', mapping, productCode)
    : [];

  // STOCK 단일부품 생산: stockPartFilter에 해당하는 부품만 표시
  if (stockFilter && stockFilter.length > 0) {
    const allowedKeys = new Set(stockFilter.map(f => f.partKey));
    const filterRows = (rows: typeof wallRows) =>
      rows.filter(row => {
        if (allowedKeys.has('본체') && row.partName.includes('본체')) return true;
        if (allowedKeys.has('C형') && row.partName.includes('C형')) return true;
        if (allowedKeys.has('D형') && row.partName.includes('D형')) return true;
        if (allowedKeys.has('마감재') && row.partName.includes('마감')) return true;
        if (allowedKeys.has('별도마감') && row.partName.includes('별도마감')) return true;
        if (allowedKeys.has('BASE') && row.partName.includes('BASE')) return true;
        return false;
      });
    wallRows = filterRows(wallRows);
    sideRows = filterRows(sideRows);
  }

  if (wallRows.length === 0 && sideRows.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">
        1. 가이드레일
      </div>

      {wallRows.length > 0 && (
        <PartTable
          title="1.1 벽면형 [130*75]"
          rows={wallRows}
          imageUrl={getBendingImageUrl('guiderail', productCode, 'wall', bendingImages)}
          lotNo={lotNo}
          baseSize={wall?.baseDimension || wall?.baseSize}
          lotNoMap={lotNoMap}
        />
      )}

      {sideRows.length > 0 && (
        <PartTable
          title="1.2 측면형 [130*125]"
          rows={sideRows}
          imageUrl={getBendingImageUrl('guiderail', productCode, 'side', bendingImages)}
          lotNo={lotNo}
          baseSize={side?.baseDimension || '135*130'}
          lotNoMap={lotNoMap}
        />
      )}
    </div>
  );
}
