'use client';

/**
 * FQC 제품검사 성적서 - 양식 기반 렌더링
 *
 * documents 시스템의 template 구조를 기반으로 렌더링:
 * - 결재라인 (3인: 작성/검토/승인)
 * - 기본정보 (7필드: 납품명, 제품명, 발주처, LOT NO, 로트크기, 검사일자, 검사자)
 * - 검사항목 테이블 (4컬럼: NO, 검사항목, 검사기준, 판정)
 * - 11개 설치 후 최종검사 항목 (모두 visual/checkbox → 적합/부적합)
 * - 종합판정 (자동 계산)
 *
 * readonly=true  → 조회 모드 (InspectionReportModal에서 사용)
 * readonly=false → 편집 모드 (ProductInspectionInputModal 대체)
 */

import { useState, useMemo, useCallback, useImperativeHandle, forwardRef } from 'react';
import { ConstructionApprovalTable } from '@/components/document-system';
import type {
  FqcTemplate,
  FqcDocumentData,
  FqcTemplateItem,
} from '../fqcActions';

// ===== Types =====

export interface FqcDocumentContentRef {
  /** 현재 입력 데이터를 document_data 형식으로 반환 */
  getInspectionData: () => {
    records: Array<{
      section_id: number | null;
      column_id: number | null;
      row_index: number;
      field_key: string;
      field_value: string | null;
    }>;
    overallJudgment: '합격' | '불합격' | null;
  };
}

interface FqcDocumentContentProps {
  /** 양식 정의 (template) */
  template: FqcTemplate;
  /** 기존 문서 데이터 (저장된 검사 결과) */
  documentData?: FqcDocumentData[];
  /** 문서번호 */
  documentNo?: string;
  /** 작성일자 */
  createdDate?: string;
  /** 기본필드 오버라이드 (API에서 auto-fill된 값) */
  basicFieldValues?: Record<string, string>;
  /** 읽기전용 모드 */
  readonly?: boolean;
}

type JudgmentValue = '적합' | '부적합' | null;

// ===== Component =====

export const FqcDocumentContent = forwardRef<FqcDocumentContentRef, FqcDocumentContentProps>(
  function FqcDocumentContent(
    {
      template,
      documentData = [],
      documentNo = '',
      createdDate = '',
      basicFieldValues = {},
      readonly = true,
    },
    ref
  ) {
    // 데이터 섹션 찾기 (items가 있는 섹션)
    const dataSection = useMemo(
      () => template.sections.find(s => s.items.length > 0),
      [template.sections]
    );

    // 판정 컬럼 ID 찾기
    const judgmentColumnId = useMemo(
      () => template.columns.find(c => c.label === '판정')?.id ?? null,
      [template.columns]
    );

    // 기존 문서 데이터에서 판정값 추출
    const initialJudgments = useMemo(() => {
      const map: Record<number, JudgmentValue> = {};
      if (!dataSection || !judgmentColumnId) return map;

      for (const d of documentData) {
        if (
          d.sectionId === dataSection.id &&
          d.columnId === judgmentColumnId &&
          d.fieldKey === 'result'
        ) {
          map[d.rowIndex] = (d.fieldValue as JudgmentValue) ?? null;
        }
      }
      return map;
    }, [documentData, dataSection, judgmentColumnId]);

    // 판정 상태 (편집 모드용)
    const [judgments, setJudgments] = useState<Record<number, JudgmentValue>>(initialJudgments);

    // 판정 토글
    const toggleJudgment = useCallback(
      (rowIndex: number, value: JudgmentValue) => {
        if (readonly) return;
        setJudgments(prev => ({
          ...prev,
          [rowIndex]: prev[rowIndex] === value ? null : value,
        }));
      },
      [readonly]
    );

    // 종합판정 자동 계산
    const overallJudgment = useMemo(() => {
      if (!dataSection) return null;
      const items = dataSection.items;
      if (items.length === 0) return null;

      const values = items.map((_, idx) => judgments[idx]);
      const hasValue = values.some(v => v !== undefined && v !== null);
      if (!hasValue) return null;
      if (values.some(v => v === '부적합')) return '불합격' as const;
      if (values.every(v => v === '적합')) return '합격' as const;
      return null;
    }, [dataSection, judgments]);

    // 기본필드 값 조회
    const getBasicFieldValue = useCallback(
      (fieldKey: string): string => {
        const field = template.basicFields.find(f => f.fieldKey === fieldKey);
        if (!field) return '';

        // bf_{id} 형식 (mng show.blade.php 호환)
        const bfKey = `bf_${field.id}`;
        if (basicFieldValues[bfKey]) return basicFieldValues[bfKey];

        const found = documentData.find(d => d.fieldKey === bfKey && !d.sectionId);
        if (found?.fieldValue) return found.fieldValue;

        // 레거시 호환: bf_{label} 형식
        const legacyKey = `bf_${field.label}`;
        if (basicFieldValues[legacyKey]) return basicFieldValues[legacyKey];
        const legacyFound = documentData.find(d => d.fieldKey === legacyKey && !d.sectionId);
        return legacyFound?.fieldValue ?? '';
      },
      [basicFieldValues, documentData, template.basicFields]
    );

    // ref를 통해 데이터 추출 (편집 모드에서 저장 시 사용)
    useImperativeHandle(ref, () => ({
      getInspectionData: () => {
        const records: Array<{
          section_id: number | null;
          column_id: number | null;
          row_index: number;
          field_key: string;
          field_value: string | null;
        }> = [];

        if (dataSection && judgmentColumnId) {
          dataSection.items.forEach((_, idx) => {
            const value = judgments[idx];
            if (value) {
              records.push({
                section_id: dataSection.id,
                column_id: judgmentColumnId,
                row_index: idx,
                field_key: 'result',
                field_value: value,
              });
            }
          });
        }

        // 종합판정
        records.push({
          section_id: null,
          column_id: null,
          row_index: 0,
          field_key: 'footer_judgement',
          field_value: overallJudgment,
        });

        return { records, overallJudgment };
      },
    }));

    // 결재라인 데이터 매핑
    const approvers = useMemo(() => {
      const lines = template.approvalLines.sort((a, b) => a.sortOrder - b.sortOrder);
      return {
        writer: lines[0] ? { name: lines[0].name, department: lines[0].department } : undefined,
        approver1: lines[1] ? { name: lines[1].name, department: lines[1].department } : undefined,
        approver2: lines[2] ? { name: lines[2].name, department: lines[2].department } : undefined,
      };
    }, [template.approvalLines]);

    // 기본필드 라벨-값 쌍
    const basicFieldPairs = useMemo(() => {
      const sorted = [...template.basicFields].sort((a, b) => a.sortOrder - b.sortOrder);
      const pairs: Array<{ label: string; value: string }> = [];
      for (const field of sorted) {
        // bf_{id} 형식 우선, 레거시 bf_{label} fallback
        const bfKey = `bf_${field.id}`;
        const legacyKey = `bf_${field.label}`;
        const value = basicFieldValues[bfKey]
          || documentData.find(d => d.fieldKey === bfKey && !d.sectionId)?.fieldValue
          || basicFieldValues[legacyKey]
          || documentData.find(d => d.fieldKey === legacyKey && !d.sectionId)?.fieldValue
          || field.defaultValue
          || '';
        pairs.push({ label: field.label, value });
      }
      return pairs;
    }, [template.basicFields, basicFieldValues, documentData]);

    // 이미지 섹션 (items가 없는 섹션)
    const imageSections = useMemo(
      () => template.sections.filter(s => s.items.length === 0 && s.imagePath),
      [template.sections]
    );

    return (
      <div className="bg-white p-8 min-h-full text-[11px]">
        {/* 헤더: 제목 (좌측) + 결재란 (우측) */}
        <div className="flex justify-between items-start mb-4">
          <div>
            <h1 className="text-2xl font-bold tracking-widest mb-2">
              {template.title || template.name || '제 품 검 사 성 적 서'}
            </h1>
            <div className="text-[10px] space-y-1">
              <div className="flex gap-4">
                <span>문서번호: <strong>{documentNo}</strong></span>
                <span>작성일자: <strong>{createdDate}</strong></span>
              </div>
            </div>
          </div>

          <ConstructionApprovalTable approvers={approvers} />
        </div>

        {/* 기본 정보 */}
        <div className="border border-gray-400 mb-4">
          <div className="bg-gray-200 text-center py-1 font-bold border-b border-gray-400">
            기본 정보
          </div>
          <table className="w-full">
            <tbody>
              {/* 2열씩 표시 */}
              {Array.from({ length: Math.ceil(basicFieldPairs.length / 2) }, (_, rowIdx) => {
                const left = basicFieldPairs[rowIdx * 2];
                const right = basicFieldPairs[rowIdx * 2 + 1];
                const isLast = rowIdx === Math.ceil(basicFieldPairs.length / 2) - 1;
                return (
                  <tr key={rowIdx} className={isLast ? '' : 'border-b border-gray-300'}>
                    {left && (
                      <>
                        <td className="bg-gray-100 px-2 py-1 w-28 font-medium border-r border-gray-300">
                          {left.label}
                        </td>
                        <td className="px-2 py-1 border-r border-gray-300">
                          {left.value || '-'}
                        </td>
                      </>
                    )}
                    {right ? (
                      <>
                        <td className="bg-gray-100 px-2 py-1 w-28 font-medium border-r border-gray-300">
                          {right.label}
                        </td>
                        <td className="px-2 py-1">{right.value || '-'}</td>
                      </>
                    ) : (
                      <td colSpan={2} />
                    )}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* 이미지 섹션 (검사 기준서 등) */}
        {imageSections.map(section => (
          <div key={section.id} className="border border-gray-400 mb-4">
            <div className="bg-gray-200 text-center py-1 font-bold border-b border-gray-400">
              {section.title || section.name}
            </div>
            <div className="p-4 flex items-center justify-center min-h-[100px]">
              {section.imagePath ? (
                <img
                  src={`${process.env.NEXT_PUBLIC_API_URL}/storage/${section.imagePath}`}
                  alt={section.name}
                  className="max-h-[300px] max-w-full object-contain"
                />
              ) : (
                <div className="text-gray-400 text-center">
                  <div className="border-2 border-dashed border-gray-300 p-8 rounded">
                    이미지 없음
                  </div>
                </div>
              )}
            </div>
          </div>
        ))}

        {/* 검사항목 테이블 */}
        {dataSection && (
          <table className="w-full border-collapse border border-gray-400 mb-4">
            <thead>
              <tr className="bg-gray-100">
                {template.columns
                  .sort((a, b) => a.sortOrder - b.sortOrder)
                  .map(col => (
                    <th
                      key={col.id}
                      className="border border-gray-400 px-2 py-1 text-center"
                      style={col.width ? { width: col.width } : undefined}
                    >
                      {col.label}
                    </th>
                  ))}
              </tr>
            </thead>
            <tbody>
              {dataSection.items
                .sort((a, b) => a.sortOrder - b.sortOrder)
                .map((item, idx) => (
                  <InspectionRow
                    key={item.id}
                    item={item}
                    rowIndex={idx}
                    judgment={judgments[idx] ?? null}
                    onToggleJudgment={toggleJudgment}
                    readonly={readonly}
                  />
                ))}

              {dataSection.items.length === 0 && (
                <tr>
                  <td
                    colSpan={template.columns.length}
                    className="border border-gray-400 px-2 py-4 text-center text-gray-400"
                  >
                    검사항목이 없습니다.
                  </td>
                </tr>
              )}

              {/* 종합판정 */}
              <tr>
                <td
                  className="border border-gray-400 bg-gray-100 px-2 py-2 font-bold text-center"
                  colSpan={template.columns.length - 1}
                >
                  종합판정
                </td>
                <td
                  className={`border border-gray-400 px-2 py-2 text-center font-bold text-sm ${
                    overallJudgment === '합격'
                      ? 'text-blue-600'
                      : overallJudgment === '불합격'
                        ? 'text-red-600'
                        : 'text-gray-400'
                  }`}
                >
                  {overallJudgment || '-'}
                </td>
              </tr>
            </tbody>
          </table>
        )}

        {/* 서명 영역 */}
        <div className="mt-8 text-center text-[10px]">
          <p>위 내용과 같이 제품검사 결과를 보고합니다.</p>
          <div className="mt-6">
            <p>{createdDate}</p>
          </div>
        </div>
      </div>
    );
  }
);

// ===== 검사항목 행 =====

interface InspectionRowProps {
  item: FqcTemplateItem;
  rowIndex: number;
  judgment: JudgmentValue;
  onToggleJudgment: (rowIndex: number, value: JudgmentValue) => void;
  readonly: boolean;
}

function InspectionRow({ item, rowIndex, judgment, onToggleJudgment, readonly }: InspectionRowProps) {
  return (
    <tr className="border-b border-gray-300">
      {/* NO */}
      <td className="border border-gray-400 px-2 py-1 text-center align-middle font-medium w-10">
        {rowIndex + 1}
      </td>
      {/* 검사항목 */}
      <td className="border border-gray-400 px-2 py-1 align-middle">
        {item.itemName}
      </td>
      {/* 검사기준 */}
      <td className="border border-gray-400 px-2 py-1 align-middle">
        {item.standard || item.frequency || '-'}
      </td>
      {/* 판정 */}
      <td className="border border-gray-400 px-1 py-1 text-center align-middle w-28">
        {readonly ? (
          <div className="flex items-center justify-center gap-1 text-[10px]">
            <span className={judgment === '적합' ? 'font-bold text-blue-600' : 'text-gray-400'}>
              {judgment === '적합' ? '■' : '□'} 적합
            </span>
            <span className={judgment === '부적합' ? 'font-bold text-red-600' : 'text-gray-400'}>
              {judgment === '부적합' ? '■' : '□'} 부적합
            </span>
          </div>
        ) : (
          <div className="flex items-center justify-center gap-2">
            <button
              type="button"
              onClick={() => onToggleJudgment(rowIndex, '적합')}
              className={`px-2 py-0.5 rounded text-[10px] border transition-colors ${
                judgment === '적합'
                  ? 'bg-blue-600 text-white border-blue-600'
                  : 'bg-white text-gray-500 border-gray-300 hover:border-blue-400'
              }`}
            >
              적합
            </button>
            <button
              type="button"
              onClick={() => onToggleJudgment(rowIndex, '부적합')}
              className={`px-2 py-0.5 rounded text-[10px] border transition-colors ${
                judgment === '부적합'
                  ? 'bg-red-600 text-white border-red-600'
                  : 'bg-white text-gray-500 border-gray-300 hover:border-red-400'
              }`}
            >
              부적합
            </button>
          </div>
        )}
      </td>
    </tr>
  );
}