import type {
  Inspection,
  InspectionStats,
  InspectionItem,
} from './types';
import { getTodayString } from '@/utils/date';

// 검사 항목 템플릿 (조인트바 예시)
export const inspectionItemsTemplate: InspectionItem[] = [
  {
    id: 'item-1',
    name: '가공상태',
    type: 'quality',
    spec: '결함 없을 것',
  },
  {
    id: 'item-2',
    name: '높이(H)',
    type: 'measurement',
    spec: '16.5 ± 1',
    unit: 'mm',
  },
  {
    id: 'item-3',
    name: '길이(L)',
    type: 'measurement',
    spec: '300 ± 4',
    unit: 'mm',
  },
];

// Mock 검사 데이터 (스크린샷 기반)
export const mockInspections: Inspection[] = [
  {
    id: '1',
    inspectionNo: 'QC-251219-01',
    inspectionType: 'IQC',
    requestDate: '2025-12-19',
    itemName: 'EGI 철골판 1.5ST',
    lotNo: 'MAT-251219-01',
    processName: '입고 검사',
    quantity: 100,
    unit: 'EA',
    status: '대기',
    inspector: undefined,
    items: [],
    remarks: '',
  },
  {
    id: '2',
    inspectionNo: 'QC-251219-02',
    inspectionType: 'PQC',
    requestDate: '2025-12-19',
    inspectionDate: '2025-12-19',
    itemName: '조인트바',
    lotNo: 'WO-251219-05',
    processName: '조립 공정',
    quantity: 50,
    unit: 'EA',
    status: '진행중',
    result: undefined,
    inspector: '홍길동',
    items: [
      {
        id: 'item-1',
        name: '가공상태',
        type: 'quality',
        spec: '결함 없을 것',
        result: '양호',
        judgment: '적합',
      },
      {
        id: 'item-2',
        name: '높이(H)',
        type: 'measurement',
        spec: '16.5 ± 1',
        unit: 'mm',
        measuredValue: 16.6,
        judgment: '적합',
      },
      {
        id: 'item-3',
        name: '길이(L)',
        type: 'measurement',
        spec: '300 ± 4',
        unit: 'mm',
        measuredValue: 301,
        judgment: '적합',
      },
    ],
    remarks: '',
  },
  {
    id: '3',
    inspectionNo: 'QC-251218-03',
    inspectionType: 'FQC',
    requestDate: '2025-12-18',
    inspectionDate: '2025-12-18',
    itemName: '방화샤터 완제품',
    lotNo: 'WO-251218-02',
    processName: '최종 검사',
    quantity: 10,
    unit: 'EA',
    status: '완료',
    result: '합격',
    inspector: '김철수',
    items: [
      {
        id: 'item-1',
        name: '가공상태',
        type: 'quality',
        spec: '결함 없을 것',
        result: '양호',
        judgment: '적합',
      },
      {
        id: 'item-2',
        name: '높이(H)',
        type: 'measurement',
        spec: '16.5 ± 1',
        unit: 'mm',
        measuredValue: 16.6,
        judgment: '적합',
      },
      {
        id: 'item-3',
        name: '길이(L)',
        type: 'measurement',
        spec: '300 ± 4',
        unit: 'mm',
        measuredValue: 301,
        judgment: '적합',
      },
    ],
    remarks: '',
    opinion: '특이사항 없음. 후공정(포장) 인계 완료함.',
    attachments: [
      {
        id: 'att-1',
        fileName: '현장_검사_사진_01.jpg',
        fileUrl: '/uploads/inspection/현장_검사_사진_01.jpg',
        fileType: 'image/jpeg',
        uploadedAt: '2025-12-18T10:30:00',
      },
    ],
  },
  {
    id: '4',
    inspectionNo: 'QC-251218-04',
    inspectionType: 'PQC',
    requestDate: '2025-12-18',
    inspectionDate: '2025-12-18',
    itemName: '슬랫 성형품',
    lotNo: 'WO-251218-01',
    processName: '성형 공정',
    quantity: 200,
    unit: 'EA',
    status: '완료',
    result: '합격',
    inspector: '이영희',
    items: [
      {
        id: 'item-1',
        name: '가공상태',
        type: 'quality',
        spec: '결함 없을 것',
        result: '양호',
        judgment: '적합',
      },
      {
        id: 'item-2',
        name: '높이(H)',
        type: 'measurement',
        spec: '16.5 ± 1',
        unit: 'mm',
        measuredValue: 16.4,
        judgment: '적합',
      },
      {
        id: 'item-3',
        name: '길이(L)',
        type: 'measurement',
        spec: '300 ± 4',
        unit: 'mm',
        measuredValue: 299,
        judgment: '적합',
      },
    ],
    remarks: '',
    opinion: '검사 완료. 이상 없음.',
  },
  {
    id: '5',
    inspectionNo: 'QC-251218-05',
    inspectionType: 'IQC',
    requestDate: '2025-12-18',
    inspectionDate: '2025-12-18',
    itemName: '스테인레스 코일',
    lotNo: 'MAT-251218-03',
    processName: '입고 검사',
    quantity: 5,
    unit: 'ROLL',
    status: '완료',
    result: '합격',
    inspector: '박민수',
    items: [
      {
        id: 'item-1',
        name: '가공상태',
        type: 'quality',
        spec: '결함 없을 것',
        result: '양호',
        judgment: '적합',
      },
      {
        id: 'item-2',
        name: '두께',
        type: 'measurement',
        spec: '1.2 ± 0.1',
        unit: 'mm',
        measuredValue: 1.19,
        judgment: '적합',
      },
      {
        id: 'item-3',
        name: '폭',
        type: 'measurement',
        spec: '1000 ± 5',
        unit: 'mm',
        measuredValue: 1001,
        judgment: '적합',
      },
    ],
    remarks: '',
    opinion: '입고 검사 완료. 품질 적합.',
  },
];

// 통계 데이터 계산
export const calculateStats = (inspections: Inspection[]): InspectionStats => {
  const today = getTodayString();

  const waitingCount = inspections.filter(i => i.status === '대기').length;
  const inProgressCount = inspections.filter(i => i.status === '진행중').length;
  const completedToday = inspections.filter(
    i => i.status === '완료' && i.inspectionDate === today
  ).length;

  const totalCompleted = inspections.filter(i => i.status === '완료').length;
  const defectCount = inspections.filter(i => i.result === '불합격').length;
  const defectRate = totalCompleted > 0 ? (defectCount / totalCompleted) * 100 : 0;

  return {
    waitingCount,
    inProgressCount,
    completedCount: completedToday,
    defectRate: Math.round(defectRate * 10) / 10,
  };
};

// 기본 통계 (mockData 기준)
export const mockStats: InspectionStats = {
  waitingCount: 1,
  inProgressCount: 1,
  completedCount: 3,
  defectRate: 0.0,
};

// 검사유형 라벨
export const inspectionTypeLabels: Record<string, string> = {
  IQC: '입고검사',
  PQC: '공정검사',
  FQC: '최종검사',
};

// 상태 컬러 매핑
export const statusColorMap: Record<string, string> = {
  대기: 'bg-gray-100 text-gray-800',
  진행중: 'bg-blue-100 text-blue-800',
  완료: 'bg-green-100 text-green-800',
};

// 판정 컬러 매핑
export const judgmentColorMap: Record<string, string> = {
  합격: 'bg-green-100 text-green-800',
  불합격: 'bg-red-100 text-red-800',
  적합: 'text-green-600',
  부적합: 'text-red-600',
};

// 측정값 판정 함수
export const judgeMeasurement = (spec: string, value: number): '적합' | '부적합' => {
  // spec 예시: "16.5 ± 1" 또는 "300 ± 4"
  const match = spec.match(/^([\d.]+)\s*±\s*([\d.]+)$/);
  if (!match) return '적합'; // 파싱 실패 시 기본 적합

  const [, targetStr, toleranceStr] = match;
  const target = parseFloat(targetStr);
  const tolerance = parseFloat(toleranceStr);

  const min = target - tolerance;
  const max = target + tolerance;

  return value >= min && value <= max ? '적합' : '부적합';
};