import React, { useState } from 'react';
import { Search, DollarSign, X, Package, Save, Edit, Trash2 } from 'lucide-react';

// 선택 관리 훅
const useListSelection = (data) => {
  const [selectedIds, setSelectedIds] = useState([]);

  const handleSelect = (id) => {
    setSelectedIds(prev =>
      prev.includes(id) ? prev.filter(i => i !== id) : [...prev, id]
    );
  };

  const handleSelectAll = () => {
    if (selectedIds.length === data.length) {
      setSelectedIds([]);
    } else {
      setSelectedIds(data.map(item => item.id));
    }
  };

  const clearSelection = () => setSelectedIds([]);

  return {
    selectedIds,
    handleSelect,
    handleSelectAll,
    clearSelection,
    isAllSelected: data.length > 0 && selectedIds.length === data.length,
    hasSelection: selectedIds.length > 0,
    isMultiSelect: selectedIds.length > 1,
    isSelected: (id) => selectedIds.includes(id),
  };
};

// ============ 단가 관리 (단일 목록 방식 - 품목마스터 연동) ============
// props.items가 전달되면 품목마스터와 연동, 없으면 기본 데이터 사용

// 기본 단가 데이터 (품목마스터 미연동 시)
const defaultPriceData = [
  { id: 1, itemType: '제품', itemCode: 'FG-SCR-STD-001', itemName: '일반스크린', spec: '3000×4000', unit: 'SET', purchasePrice: 450000, processingCost: 85000, lossRate: 3, marginRate: 25, sellingPrice: 680000, validFrom: '2025-01-01', status: '활성' },
  { id: 2, itemType: '제품', itemCode: 'FG-SCR-PRM-001', itemName: '방화스크린', spec: '3500×4500', unit: 'SET', purchasePrice: 520000, processingCost: 95000, lossRate: 3, marginRate: 25, sellingPrice: 768750, validFrom: '2025-01-01', status: '활성' },
  { id: 3, itemType: '제품', itemCode: 'FG-SLT-AL-001', itemName: '알루미늄슬랫셔터', spec: '4000×3500', unit: 'SET', purchasePrice: 380000, processingCost: 70000, lossRate: 2, marginRate: 22, sellingPrice: 548780, validFrom: '2025-01-01', status: '활성' },
  { id: 4, itemType: '부품', itemCode: 'GR-001', itemName: '가이드레일 130×80', spec: '130×80×2438', unit: 'EA', purchasePrice: 45000, processingCost: 5000, lossRate: 3, marginRate: 20, sellingPrice: 60000, validFrom: '2025-01-01', status: '활성' },
  { id: 5, itemType: '부품', itemCode: 'CASE-001', itemName: '케이스 철재', spec: '표준형', unit: 'EA', purchasePrice: 35000, processingCost: 10000, lossRate: 2, marginRate: 25, sellingPrice: 56250, validFrom: '2025-01-01', status: '활성' },
  { id: 6, itemType: '부품', itemCode: 'MOTOR-001', itemName: '모터 0.4KW', spec: '0.4KW', unit: 'EA', purchasePrice: 120000, processingCost: 10000, lossRate: 0, marginRate: 15, sellingPrice: 149500, validFrom: '2025-01-01', status: '활성' },
  { id: 7, itemType: '부품', itemCode: 'CTL-001', itemName: '제어기 기본형', spec: '기본형', unit: 'EA', purchasePrice: 80000, processingCost: 5000, lossRate: 0, marginRate: 20, sellingPrice: 102000, validFrom: '2025-01-01', status: '활성' },
  { id: 8, itemType: '부자재', itemCode: 'SCR-0.3T', itemName: '스크린원단', spec: '0.3T', unit: 'M', purchasePrice: 8500, processingCost: 500, lossRate: 5, marginRate: 18, sellingPrice: 10827, validFrom: '2025-01-01', status: '활성' },
  { id: 9, itemType: '부자재', itemCode: 'SLT-75mm', itemName: '슬랫', spec: '75mm', unit: 'EA', purchasePrice: 3500, processingCost: 200, lossRate: 2, marginRate: 20, sellingPrice: 4536, validFrom: '2025-01-01', status: '활성' },
  { id: 10, itemType: '원자재', itemCode: 'STEEL-1.2T', itemName: '철판', spec: '1.2T', unit: 'KG', purchasePrice: 1200, processingCost: 0, lossRate: 5, marginRate: 15, sellingPrice: 1449, validFrom: '2025-01-01', status: '활성' },
  { id: 11, itemType: '원자재', itemCode: 'EGI-1.6T', itemName: '아연도금강판', spec: '1.6T', unit: 'KG', purchasePrice: 1500, processingCost: 0, lossRate: 5, marginRate: 15, sellingPrice: 1811, validFrom: '2025-01-01', status: '활성' },
  { id: 12, itemType: '소모품', itemCode: '볼트-M8×20', itemName: '볼트', spec: 'M8×20', unit: 'EA', purchasePrice: 120, processingCost: 0, lossRate: 0, marginRate: 25, sellingPrice: 150, validFrom: '2025-01-01', status: '활성' },
];

const PriceListSimple = ({ onNavigate, items: externalItems, onUpdatePrice }) => {
  const [search, setSearch] = useState('');
  const [itemTypeFilter, setItemTypeFilter] = useState('전체');
  const [showModal, setShowModal] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null);

  // ===== 품목별 통합 단가 데이터 (품목마스터 연동) =====
  // externalItems가 전달되면 품목마스터와 연동, 없으면 기본 데이터 사용
  const [localPriceData, setLocalPriceData] = useState(defaultPriceData);

  // 품목마스터 연동: externalItems가 있으면 품목 정보를 단가 데이터로 변환
  const priceData = externalItems ? externalItems.map((item, idx) => ({
    id: item.id || idx + 1,
    itemType: item.itemType || '기타',
    itemCode: item.itemCode,
    itemName: item.itemName,
    spec: item.spec || '-',
    unit: item.unit || 'EA',
    purchasePrice: item.purchasePrice || item.unitPrice || 0,
    processingCost: item.processingCost || 0,
    lossRate: item.lossRate || 0,
    marginRate: item.marginRate || 20,
    sellingPrice: item.sellingPrice || item.purchasePrice || 0,
    validFrom: item.validFrom || item.createdAt || new Date().toISOString().slice(0, 10),
    status: item.isActive !== false ? '활성' : '비활성',
  })) : localPriceData;

  // 내부 상태 업데이트 (품목마스터 미연동 시)
  const setPriceData = (updater) => {
    if (externalItems && onUpdatePrice) {
      // 품목마스터 연동 시 부모 컴포넌트로 업데이트 전달
      const newData = typeof updater === 'function' ? updater(priceData) : updater;
      onUpdatePrice(newData);
    } else {
      // 품목마스터 미연동 시 로컬 상태 업데이트
      setLocalPriceData(updater);
    }
  };

  // ===== 거래처 그룹별 할인율 (별도 마스터) =====
  const [customerGroups, setCustomerGroups] = useState([
    { id: 1, groupCode: 'VIP', groupName: 'VIP 고객', discountRate: 10, description: '연간 거래액 1억 이상', customerCount: 5 },
    { id: 2, groupCode: 'GOLD', groupName: '골드 고객', discountRate: 7, description: '연간 거래액 5천만원 이상', customerCount: 12 },
    { id: 3, groupCode: 'SILVER', groupName: '실버 고객', discountRate: 5, description: '연간 거래액 1천만원 이상', customerCount: 28 },
    { id: 4, groupCode: 'NORMAL', groupName: '일반 고객', discountRate: 0, description: '일반 거래 고객', customerCount: 156 },
  ]);

  // ===== 품목유형 탭 =====
  const itemTypeTabs = ['전체', '제품', '부품', '부자재', '원자재', '소모품'];

  // 품목유형별 카운트
  const getTypeCount = (type) => {
    if (type === '전체') return priceData.length;
    return priceData.filter(p => p.itemType === type).length;
  };

  // 필터링 및 정렬 (ID 내림차순)
  const filteredData = [...priceData]
    .sort((a, b) => b.id - a.id)
    .filter(p => itemTypeFilter === '전체' || p.itemType === itemTypeFilter)
    .filter(p => p.itemCode.toLowerCase().includes(search.toLowerCase()) || p.itemName.includes(search) || p.spec?.includes(search));

  // 체크박스 선택 관리
  const { selectedIds, handleSelect, handleSelectAll, clearSelection, isAllSelected, hasSelection, isMultiSelect, isSelected } = useListSelection(filteredData);

  // ===== 통계 =====
  const totalItems = priceData.length;
  const activeItems = priceData.filter(p => p.status === '활성').length;

  // ===== 핸들러 =====
  const openEditModal = (item) => {
    setSelectedItem(item);
    setShowModal(true);
  };

  const handleSavePrice = (updatedItem) => {
    setPriceData(prev => prev.map(p => p.id === updatedItem.id ? { ...updatedItem } : p));
    setShowModal(false);
  };

  // 삭제 핸들러
  const handleDelete = (id) => {
    if (window.confirm('해당 단가 정보를 삭제하시겠습니까?')) {
      setPriceData(prev => prev.filter(p => p.id !== id));
      clearSelection();
    }
  };

  // 선택 삭제 핸들러
  const handleDeleteSelected = () => {
    if (window.confirm(`선택한 ${selectedIds.length}건을 삭제하시겠습니까?`)) {
      setPriceData(prev => prev.filter(p => !selectedIds.includes(p.id)));
      clearSelection();
    }
  };

  return (
    <div className="space-y-4">
      {/* 헤더 */}
      <div className="space-y-3">
        <h1 className="text-xl font-bold flex items-center gap-2">
          <DollarSign className="w-6 h-6 text-blue-500" />
          단가 목록
        </h1>
      </div>

      {/* 통계 카드 */}
      <div className="grid grid-cols-4 gap-4">
        <div className="bg-white rounded-xl border p-4">
          <p className="text-sm text-gray-500 mb-1">전체 품목</p>
          <p className="text-2xl font-bold">{totalItems}</p>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <p className="text-sm text-gray-500 mb-1">활성 단가</p>
          <p className="text-2xl font-bold">{activeItems}</p>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <p className="text-sm text-gray-500 mb-1">거래처그룹</p>
          <p className="text-2xl font-bold">{customerGroups.length}</p>
        </div>
        <div className="bg-white rounded-xl border p-4">
          <p className="text-sm text-gray-500 mb-1">품목유형</p>
          <p className="text-2xl font-bold">{itemTypeTabs.length - 1}</p>
        </div>
      </div>

      {/* 검색 */}
      <div className="relative">
        <Search className="absolute left-4 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
        <input
          type="text"
          placeholder="품목코드, 품목명, 규격 검색..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="w-full pl-12 pr-4 py-3 border rounded-xl"
        />
      </div>

      {/* 메인 테이블 */}
      <div className="bg-white rounded-xl border overflow-hidden">
        {/* 품목유형 탭 + 선택 삭제 버튼 (칩 스타일) */}
        <div className="px-4 py-3 border-b bg-gray-50 flex justify-between items-center">
          <div className="flex flex-wrap gap-2">
            {itemTypeTabs.map(tab => (
              <button
                key={tab}
                onClick={() => setItemTypeFilter(tab)}
                className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium rounded-full border transition-colors ${
                  itemTypeFilter === tab
                    ? 'bg-gray-900 text-white border-gray-900'
                    : 'bg-white text-gray-600 border-gray-300 hover:bg-gray-50 hover:border-gray-400'
                }`}
              >
                {tab}
                <span className={`text-xs px-1.5 py-0.5 rounded-full ${
                  itemTypeFilter === tab
                    ? 'bg-gray-700 text-white'
                    : 'bg-gray-100 text-gray-500'
                }`}>
                  {getTypeCount(tab)}
                </span>
              </button>
            ))}
          </div>
          {isMultiSelect && (
            <button
              onClick={handleDeleteSelected}
              className="px-3 py-1.5 bg-red-500 text-white text-sm rounded-lg hover:bg-red-600 flex items-center gap-1"
            >
              <Trash2 className="w-4 h-4" />
              선택 삭제 ({selectedIds.length})
            </button>
          )}
        </div>

        {/* 단가 목록 테이블 */}
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-3 text-center">
                  <input
                    type="checkbox"
                    checked={isAllSelected}
                    onChange={handleSelectAll}
                    className="w-4 h-4 rounded border-gray-300"
                  />
                </th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">번호</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목유형</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목코드</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">품목명</th>
                <th className="px-4 py-3 text-left text-xs font-medium text-gray-500">규격</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">단위</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">매입단가</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">가공비</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">LOSS(%)</th>
                <th className="px-4 py-3 text-right text-xs font-medium text-gray-500">판매단가</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">마진율</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">적용일</th>
                <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">상태</th>
                {hasSelection && (
                  <th className="px-4 py-3 text-center text-xs font-medium text-gray-500">작업</th>
                )}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200">
              {filteredData.map((item, idx) => (
                <tr key={item.id} className={`hover:bg-gray-50 ${isSelected(item.id) ? 'bg-blue-50' : ''}`}>
                  <td className="px-4 py-3 text-center">
                    <input
                      type="checkbox"
                      checked={isSelected(item.id)}
                      onChange={() => handleSelect(item.id)}
                      className="w-4 h-4 rounded border-gray-300"
                    />
                  </td>
                  <td className="px-4 py-3 text-sm text-gray-500">{filteredData.length - idx}</td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-0.5 rounded text-xs font-medium ${
                      item.itemType === '제품' ? 'bg-blue-100 text-blue-700' :
                      item.itemType === '부품' ? 'bg-orange-100 text-orange-700' :
                      item.itemType === '부자재' ? 'bg-green-100 text-green-700' :
                      item.itemType === '원자재' ? 'bg-purple-100 text-purple-700' :
                      'bg-gray-100 text-gray-700'
                    }`}>
                      {item.itemType}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-sm font-mono text-gray-900">{item.itemCode}</td>
                  <td className="px-4 py-3 text-sm text-gray-900">{item.itemName}</td>
                  <td className="px-4 py-3 text-sm text-gray-600">{item.spec || '-'}</td>
                  <td className="px-4 py-3 text-sm text-center text-gray-600">{item.unit}</td>
                  <td className="px-4 py-3 text-sm text-right font-medium text-gray-900">
                    {item.purchasePrice ? `${item.purchasePrice.toLocaleString()}` : '-'}
                  </td>
                  <td className="px-4 py-3 text-sm text-right text-gray-600">
                    {item.processingCost ? `${item.processingCost.toLocaleString()}` : '-'}
                  </td>
                  <td className="px-4 py-3 text-sm text-center text-gray-600">
                    {item.lossRate || 0}%
                  </td>
                  <td className="px-4 py-3 text-sm text-right font-medium text-blue-600">
                    {item.sellingPrice ? `${item.sellingPrice.toLocaleString()}` : '-'}
                  </td>
                  <td className="px-4 py-3 text-sm text-center text-green-600 font-medium">
                    {item.marginRate || 0}%
                  </td>
                  <td className="px-4 py-3 text-sm text-center text-gray-600">
                    {item.validFrom || '-'}
                  </td>
                  <td className="px-4 py-3 text-center">
                    <span className={`px-2 py-0.5 rounded text-xs font-medium ${
                      item.status === '활성' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
                    }`}>
                      {item.status}
                    </span>
                  </td>
                  {hasSelection && (
                    <td className="px-4 py-3 text-center">
                      {isSelected(item.id) && (
                        <div className="flex items-center justify-center gap-1">
                          <button
                            onClick={() => openEditModal(item)}
                            className="px-2 py-1 text-xs bg-blue-100 text-blue-700 rounded hover:bg-blue-200"
                          >
                            수정
                          </button>
                          <button
                            onClick={() => handleDelete(item.id)}
                            className="px-2 py-1 text-xs bg-red-100 text-red-700 rounded hover:bg-red-200"
                          >
                            삭제
                          </button>
                        </div>
                      )}
                    </td>
                  )}
                </tr>
              ))}
              {filteredData.length === 0 && (
                <tr>
                  <td colSpan={hasSelection ? 15 : 14} className="px-4 py-8 text-center text-gray-500">
                    등록된 단가가 없습니다.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* 단가 수정 모달 */}
      {showModal && selectedItem && (
        <PriceEditModal
          item={selectedItem}
          onClose={() => setShowModal(false)}
          onSave={handleSavePrice}
        />
      )}
    </div>
  );
};

// ===== 단가 수정 모달 =====
const PriceEditModal = ({ item, onClose, onSave }) => {
  const [formData, setFormData] = useState({
    validFrom: item.validFrom || new Date().toISOString().slice(0, 10),
    supplier: item.supplier || '',
    purchasePrice: item.purchasePrice || 0,
    processingCost: item.processingCost || 0,
    lossRate: item.lossRate || 0,
    marginRate: item.marginRate || 0,
    sellingPrice: item.sellingPrice || 0,
    note: item.note || '',
  });

  // 원가 계산
  const subtotal = formData.purchasePrice + formData.processingCost;
  const lossAppliedCost = Math.round(subtotal * (1 + formData.lossRate / 100));

  // 마진율로 판매단가 자동 계산
  const handleMarginRateChange = (rate) => {
    const newSellingPrice = Math.round(lossAppliedCost * (1 + rate / 100));
    setFormData(prev => ({
      ...prev,
      marginRate: rate,
      sellingPrice: newSellingPrice,
    }));
  };

  // 판매단가로 마진율 자동 계산
  const handleSellingPriceChange = (price) => {
    const newMarginRate = lossAppliedCost > 0 ? ((price - lossAppliedCost) / lossAppliedCost * 100) : 0;
    setFormData(prev => ({
      ...prev,
      sellingPrice: price,
      marginRate: parseFloat(newMarginRate.toFixed(1)),
    }));
  };

  // 저장
  const handleSave = () => {
    onSave({
      ...item,
      ...formData,
    });
  };

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-xl shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        {/* 헤더 */}
        <div className="flex justify-between items-center p-4 border-b sticky top-0 bg-white z-10">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 bg-green-100 rounded-lg flex items-center justify-center">
              <DollarSign className="w-4 h-4 text-green-600" />
            </div>
            <h3 className="text-lg font-bold">단가 정보</h3>
          </div>
          <button onClick={onClose} className="p-1 hover:bg-gray-100 rounded">
            <X className="w-5 h-5 text-gray-500" />
          </button>
        </div>

        {/* 품목 정보 */}
        <div className="p-4">
          <div className="bg-blue-50 rounded-lg p-4 border border-blue-100">
            <div className="flex items-center gap-2 mb-3">
              <Package className="w-4 h-4 text-blue-600" />
              <span className="font-medium text-blue-900">품목 정보</span>
            </div>
            <div className="grid grid-cols-4 gap-4 text-sm">
              <div>
                <span className="text-gray-500">품목코드</span>
                <p className="font-mono font-medium mt-1">{item.itemCode}</p>
              </div>
              <div>
                <span className="text-gray-500">품목명</span>
                <p className="font-medium mt-1">{item.itemName}</p>
              </div>
              <div>
                <span className="text-gray-500">품목유형</span>
                <p className="font-medium mt-1">{item.itemType}</p>
              </div>
              <div>
                <span className="text-gray-500">단위</span>
                <p className="font-medium mt-1">{item.unit}</p>
              </div>
            </div>
          </div>
        </div>

        {/* 단가 정보 */}
        <div className="p-4 pt-0 space-y-4">
          {/* 적용일/공급업체 */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-sm text-gray-700 mb-1">적용일</label>
              <input
                type="date"
                value={formData.validFrom}
                onChange={(e) => setFormData(prev => ({ ...prev, validFrom: e.target.value }))}
                className="w-full border rounded-lg px-3 py-2 text-sm"
              />
            </div>
            <div>
              <label className="block text-sm text-gray-700 mb-1">공급업체</label>
              <input
                type="text"
                value={formData.supplier}
                onChange={(e) => setFormData(prev => ({ ...prev, supplier: e.target.value }))}
                placeholder="공급업체명"
                className="w-full border rounded-lg px-3 py-2 text-sm"
              />
            </div>
          </div>

          {/* 원가 계산 섹션 */}
          <div className="bg-gray-50 rounded-lg p-4">
            <div className="text-sm font-medium text-gray-700 mb-3">원가 계산</div>
            <div className="grid grid-cols-3 gap-4">
              <div>
                <label className="block text-xs text-gray-500 mb-1">입고가 (매입단가)</label>
                <div className="flex items-center gap-1">
                  <input
                    type="number"
                    value={formData.purchasePrice}
                    onChange={(e) => setFormData(prev => ({ ...prev, purchasePrice: parseInt(e.target.value) || 0 }))}
                    className="flex-1 border rounded px-2 py-1.5 text-sm text-right"
                  />
                  <span className="text-xs text-gray-500">원</span>
                </div>
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">가공비</label>
                <div className="flex items-center gap-1">
                  <input
                    type="number"
                    value={formData.processingCost}
                    onChange={(e) => setFormData(prev => ({ ...prev, processingCost: parseInt(e.target.value) || 0 }))}
                    className="flex-1 border rounded px-2 py-1.5 text-sm text-right"
                  />
                  <span className="text-xs text-gray-500">원</span>
                </div>
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">LOSS율</label>
                <div className="flex items-center gap-1">
                  <input
                    type="number"
                    value={formData.lossRate}
                    onChange={(e) => setFormData(prev => ({ ...prev, lossRate: parseFloat(e.target.value) || 0 }))}
                    className="flex-1 border rounded px-2 py-1.5 text-sm text-right"
                  />
                  <span className="text-xs text-gray-500">%</span>
                </div>
              </div>
            </div>
            <div className="mt-3 pt-3 border-t flex justify-between items-center text-sm">
              <span className="text-gray-600">원가 합계 (LOSS 적용)</span>
              <span className="font-bold text-gray-900">{lossAppliedCost.toLocaleString()}원</span>
            </div>
          </div>

          {/* 마진 계산 섹션 */}
          <div className="bg-green-50 rounded-lg p-4">
            <div className="text-sm font-medium text-gray-700 mb-3">마진 계산</div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-xs text-gray-500 mb-1">마진율 (%)</label>
                <div className="flex items-center gap-1">
                  <input
                    type="number"
                    value={formData.marginRate}
                    onChange={(e) => handleMarginRateChange(parseFloat(e.target.value) || 0)}
                    className="flex-1 border rounded px-2 py-1.5 text-sm text-right"
                  />
                  <span className="text-xs text-gray-500">%</span>
                </div>
              </div>
              <div>
                <label className="block text-xs text-gray-500 mb-1">판매단가</label>
                <div className="flex items-center gap-1">
                  <input
                    type="number"
                    value={formData.sellingPrice}
                    onChange={(e) => handleSellingPriceChange(parseInt(e.target.value) || 0)}
                    className="flex-1 border rounded px-2 py-1.5 text-sm text-right font-medium text-blue-600"
                  />
                  <span className="text-xs text-gray-500">원</span>
                </div>
              </div>
            </div>
            <div className="mt-3 pt-3 border-t flex justify-between items-center text-sm">
              <span className="text-gray-600">마진 금액</span>
              <span className="font-bold text-green-600">+{(formData.sellingPrice - lossAppliedCost).toLocaleString()}원</span>
            </div>
          </div>

          {/* 비고 */}
          <div>
            <label className="block text-sm text-gray-700 mb-1">비고</label>
            <textarea
              value={formData.note}
              onChange={(e) => setFormData(prev => ({ ...prev, note: e.target.value }))}
              rows={2}
              className="w-full border rounded-lg px-3 py-2 text-sm"
              placeholder="메모 입력..."
            />
          </div>
        </div>

        {/* 푸터 */}
        <div className="flex justify-end gap-2 p-4 border-t bg-gray-50">
          <button onClick={onClose} className="px-4 py-2 border rounded-lg text-gray-700 hover:bg-gray-100">
            취소
          </button>
          <button onClick={handleSave} className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 flex items-center gap-2">
            <Save className="w-4 h-4" /> 저장
          </button>
        </div>
      </div>
    </div>
  );
};

export default PriceListSimple;
