/**
 * 품목 수정 페이지
 */

'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import ItemForm from '@/components/items/ItemForm';
import type { ItemMaster } from '@/types/item';
import type { CreateItemFormData } from '@/lib/utils/validation';

// Mock 데이터 (API 연동 전 임시)
const mockItems: ItemMaster[] = [
  {
    id: '1',
    itemCode: 'KD-FG-001',
    itemName: '스크린 제품 A',
    itemType: 'FG',
    unit: 'EA',
    specification: '2000x2000',
    isActive: true,
    category1: '본체부품',
    category2: '가이드시스템',
    salesPrice: 150000,
    purchasePrice: 100000,
    marginRate: 33.3,
    processingCost: 20000,
    laborCost: 15000,
    installCost: 10000,
    productCategory: 'SCREEN',
    lotAbbreviation: 'KD',
    note: '스크린 제품 샘플입니다.',
    safetyStock: 10,
    leadTime: 7,
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-01-10T00:00:00Z',
    updatedAt: '2025-01-12T00:00:00Z',
    bom: [
      {
        id: 'bom-1',
        childItemCode: 'KD-PT-001',
        childItemName: '가이드레일(벽면형)',
        quantity: 2,
        unit: 'EA',
        unitPrice: 35000,
        quantityFormula: 'H / 1000',
      },
      {
        id: 'bom-2',
        childItemCode: 'KD-PT-002',
        childItemName: '절곡품 샘플',
        quantity: 4,
        unit: 'EA',
        unitPrice: 30000,
        isBending: true,
      },
      {
        id: 'bom-3',
        childItemCode: 'KD-SM-001',
        childItemName: '볼트 M6x20',
        quantity: 20,
        unit: 'EA',
        unitPrice: 50,
      },
    ],
  },
  {
    id: '2',
    itemCode: 'KD-PT-001',
    itemName: '가이드레일(벽면형)',
    itemType: 'PT',
    unit: 'EA',
    specification: '2438mm',
    isActive: true,
    category1: '본체부품',
    category2: '가이드시스템',
    category3: '가이드레일',
    salesPrice: 50000,
    purchasePrice: 35000,
    marginRate: 30,
    partType: 'ASSEMBLY',
    partUsage: 'GUIDE_RAIL',
    installationType: '벽면형',
    assemblyType: 'M',
    assemblyLength: '2438',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-01-10T00:00:00Z',
  },
  {
    id: '3',
    itemCode: 'KD-PT-002',
    itemName: '절곡품 샘플',
    itemType: 'PT',
    unit: 'EA',
    specification: 'EGI 1.55T',
    isActive: true,
    partType: 'BENDING',
    material: 'EGI 1.55T',
    length: '2000',
    salesPrice: 30000,
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-01-10T00:00:00Z',
  },
  {
    id: '4',
    itemCode: 'KD-RM-001',
    itemName: 'SPHC-SD',
    itemType: 'RM',
    unit: 'KG',
    specification: '1.6T x 1219 x 2438',
    isActive: true,
    category1: '철강재',
    purchasePrice: 1500,
    material: 'SPHC-SD',
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-01-10T00:00:00Z',
  },
  {
    id: '5',
    itemCode: 'KD-SM-001',
    itemName: '볼트 M6x20',
    itemType: 'SM',
    unit: 'EA',
    specification: 'M6x20',
    isActive: true,
    category1: '구조재/부속품',
    category2: '볼트/너트',
    purchasePrice: 50,
    currentRevision: 0,
    isFinal: false,
    createdAt: '2025-01-10T00:00:00Z',
  },
];

export default function EditItemPage() {
  const params = useParams();
  const router = useRouter();
  const [item, setItem] = useState<ItemMaster | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // TODO: API 연동 시 fetchItemByCode() 호출
    const fetchItem = async () => {
      setIsLoading(true);
      try {
        // params.id 타입 체크
        if (!params.id || typeof params.id !== 'string') {
          alert('잘못된 품목 ID입니다.');
          router.push('/items');
          return;
        }

        // Mock: 데이터 조회
        const itemCode = decodeURIComponent(params.id);
        const foundItem = mockItems.find((item) => item.itemCode === itemCode);

        if (foundItem) {
          setItem(foundItem);
        } else {
          alert('품목을 찾을 수 없습니다.');
          router.push('/items');
        }
      } catch {
        alert('품목 조회에 실패했습니다.');
        router.push('/items');
      } finally {
        setIsLoading(false);
      }
    };

    fetchItem();
  }, [params.id, router]);

  const handleSubmit = async (data: CreateItemFormData) => {
    // TODO: API 연동 시 updateItem() 호출
    console.log('품목 수정 데이터:', data);

    // Mock: 성공 메시지
    alert(`품목 "${data.itemName}" (${data.itemCode})이(가) 수정되었습니다.`);

    // API 연동 예시:
    // const updatedItem = await updateItem(item.itemCode, data);
    // router.push(`/items/${updatedItem.itemCode}`);
  };

  if (isLoading) {
    return (
      <div className="p-6">
        <div className="text-center py-8">로딩 중...</div>
      </div>
    );
  }

  if (!item) {
    return null;
  }

  return (
    <div className="p-6">
      <ItemForm mode="edit" initialData={item} onSubmit={handleSubmit} />
    </div>
  );
}