'use client';

/**
 * 중간검사 성적서 공통 유틸리티 및 컴포넌트
 *
 * 5개 InspectionContent 컴포넌트에서 공유하는 코드:
 * - 타입 정의 (CheckStatus, InspectionContentRef 등)
 * - 상태 변환 함수 (convertToCheckStatus, convertToGapResult)
 * - UI 컴포넌트 (renderCheckbox, ApprovalTable, InspectionFooter)
 * - 날짜 유틸, 공통 스타일
 */

import { ReactNode } from 'react';
import type { WorkOrder } from '../types';
import type { InspectionSetting } from '@/types/process';

// ===== 공통 타입 =====

export type CheckStatus = '양호' | '불량' | null;
export type GapResult = 'OK' | 'NG' | null;

export interface InspectionContentRef {
  getInspectionData: () => unknown;
}

// ===== 상태 변환 함수 =====

export const convertToCheckStatus = (status: 'good' | 'bad' | null | undefined): CheckStatus => {
  if (status === 'good') return '양호';
  if (status === 'bad') return '불량';
  return null;
};

export const convertToGapResult = (status: 'ok' | 'ng' | null | undefined): GapResult => {
  if (status === 'ok') return 'OK';
  if (status === 'ng') return 'NG';
  return null;
};

// ===== 날짜 유틸 =====

export function getFullDate(): string {
  return new Date().toLocaleDateString('ko-KR', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
  });
}

export function getToday(): string {
  return new Date().toLocaleDateString('ko-KR', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  }).replace(/\. /g, '-').replace('.', '');
}

// ===== 공통 스타일 =====

export const INPUT_CLASS = 'w-full text-center border-0 bg-transparent focus:outline-none focus:ring-1 focus:ring-blue-500 rounded text-xs';

export const DEFAULT_ROW_COUNT = 6;

// ===== 공통 order 정보 추출 =====

export function getOrderInfo(order: WorkOrder) {
  return {
    documentNo: order.workOrderNo || 'ABC123',
    primaryAssignee: order.assignees?.find(a => a.isPrimary)?.name || order.assignee || '-',
  };
}

// ===== PDF 호환 체크박스 =====

export function InspectionCheckbox({
  checked,
  onClick,
  readOnly = false,
}: {
  checked: boolean;
  onClick: () => void;
  readOnly?: boolean;
}) {
  return (
    <span
      className={`inline-flex items-center justify-center w-3 h-3 border rounded-sm text-[8px] leading-none cursor-pointer select-none ${
        checked ? 'border-gray-600 bg-gray-700 text-white' : 'border-gray-400 bg-white'
      }`}
      onClick={() => !readOnly && onClick()}
      role="checkbox"
      aria-checked={checked}
    >
      {checked ? '✓' : ''}
    </span>
  );
}

// ===== 양호/불량 체크 셀 =====

export function CheckStatusCell({
  value,
  onToggle,
  readOnly = false,
  rowSpan,
}: {
  value: CheckStatus;
  onToggle: (v: CheckStatus) => void;
  readOnly?: boolean;
  rowSpan?: number;
}) {
  return (
    <td className="border border-gray-400 p-1" rowSpan={rowSpan}>
      <div className="flex flex-col items-center gap-0.5">
        <label className="flex items-center gap-0.5 cursor-pointer text-xs whitespace-nowrap">
          <InspectionCheckbox
            checked={value === '양호'}
            onClick={() => onToggle(value === '양호' ? null : '양호')}
            readOnly={readOnly}
          />
          양호
        </label>
        <label className="flex items-center gap-0.5 cursor-pointer text-xs whitespace-nowrap">
          <InspectionCheckbox
            checked={value === '불량'}
            onClick={() => onToggle(value === '불량' ? null : '불량')}
            readOnly={readOnly}
          />
          불량
        </label>
      </div>
    </td>
  );
}

// ===== 결재란 =====

export function ApprovalTable({ primaryAssignee }: { primaryAssignee: string }) {
  return (
    <table className="border-collapse text-sm flex-shrink-0">
      <tbody>
        <tr>
          <td className="border border-gray-400 px-4 py-1 text-center align-middle" rowSpan={3}>결<br/>재</td>
          <td className="border border-gray-400 px-6 py-1 text-center">작성</td>
          <td className="border border-gray-400 px-6 py-1 text-center">승인</td>
          <td className="border border-gray-400 px-6 py-1 text-center">승인</td>
          <td className="border border-gray-400 px-6 py-1 text-center">승인</td>
        </tr>
        <tr>
          <td className="border border-gray-400 px-6 py-3 text-center">{primaryAssignee}</td>
          <td className="border border-gray-400 px-6 py-3 text-center text-gray-400">이름</td>
          <td className="border border-gray-400 px-6 py-3 text-center text-gray-400">이름</td>
          <td className="border border-gray-400 px-6 py-3 text-center text-gray-400">이름</td>
        </tr>
        <tr>
          <td className="border border-gray-400 px-6 py-1 text-center whitespace-nowrap">부서명</td>
          <td className="border border-gray-400 px-6 py-1 text-center whitespace-nowrap">부서명</td>
          <td className="border border-gray-400 px-6 py-1 text-center whitespace-nowrap">부서명</td>
          <td className="border border-gray-400 px-6 py-1 text-center whitespace-nowrap">부서명</td>
        </tr>
      </tbody>
    </table>
  );
}

// ===== 부적합 내용 + 종합판정 하단 =====

export function InspectionFooter({
  readOnly = false,
  overallResult,
  inadequateContent,
  onInadequateContentChange,
}: {
  readOnly?: boolean;
  overallResult: '합격' | '불합격' | null;
  inadequateContent: string;
  onInadequateContentChange: (v: string) => void;
}) {
  return (
    <table className="w-full border-collapse text-xs">
      <tbody>
        <tr>
          <td className="border border-gray-400 bg-gray-100 px-3 py-2 font-medium w-24 align-middle text-center">부적합 내용</td>
          <td className="border border-gray-400 px-3 py-2">
            <textarea
              value={inadequateContent}
              onChange={(e) => !readOnly && onInadequateContentChange(e.target.value)}
              disabled={readOnly}
              className="w-full border-0 bg-transparent focus:outline-none focus:ring-1 focus:ring-blue-500 rounded text-xs resize-none"
              rows={2}
            />
          </td>
          <td className="border border-gray-400 bg-gray-100 px-3 py-2 font-medium text-center w-24">종합판정</td>
          <td className={`border border-gray-400 px-3 py-2 text-center font-bold text-sm w-24 ${
            overallResult === '합격' ? 'text-blue-600' : overallResult === '불합격' ? 'text-red-600' : 'text-gray-400'
          }`}>
            {overallResult || '합격'}
          </td>
        </tr>
      </tbody>
    </table>
  );
}

// ===== 기본 레이아웃 래퍼 =====

export function InspectionLayout({
  title,
  documentNo,
  fullDate,
  primaryAssignee,
  children,
}: {
  title: string;
  documentNo: string;
  fullDate: string;
  primaryAssignee: string;
  children: ReactNode;
}) {
  return (
    <div className="p-6 bg-white">
      {/* 헤더 영역 */}
      <div className="flex justify-between items-start mb-6">
        <div>
          <h1 className="text-2xl font-bold">{title}</h1>
          <p className="text-xs text-gray-500 mt-1 whitespace-nowrap">
            문서번호: {documentNo} | 작성일자: {fullDate}
          </p>
        </div>
        <ApprovalTable primaryAssignee={primaryAssignee} />
      </div>
      {children}
    </div>
  );
}

// ===== 판정 셀 =====

export function JudgmentCell({ judgment, rowSpan }: { judgment: '적' | '부' | null; rowSpan?: number }) {
  return (
    <td className={`border border-gray-400 p-1 text-center font-bold ${
      judgment === '적' ? 'text-blue-600' : judgment === '부' ? 'text-red-600' : 'text-gray-300'
    }`} rowSpan={rowSpan}>
      {judgment || '-'}
    </td>
  );
}

// ===== 중간검사 기준서 섹션 =====

export function InspectionStandardSection({
  inspectionSetting,
  children,
}: {
  inspectionSetting?: InspectionSetting;
  children: ReactNode;
}) {
  const standardName = inspectionSetting?.standardName;
  const standardImage = inspectionSetting?.inspectionStandardImage;

  return (
    <>
      <div className="mb-1 font-bold text-sm">
        ■ 중간검사 기준서{standardName ? ` ${standardName}` : ''}
      </div>
      {standardImage ? (
        <div className="w-full mb-6">
          <img src={standardImage} alt="중간검사 기준서" className="w-full border border-gray-400 object-contain" />
        </div>
      ) : (
        children
      )}
    </>
  );
}

// ===== 종합판정 계산 =====

export function calculateOverallResult(judgments: ('적' | '부' | null)[]): '합격' | '불합격' | null {
  if (judgments.some(j => j === '부')) return '불합격';
  if (judgments.every(j => j === '적')) return '합격';
  return null;
}