import React, { useState } from 'react';
import {
  FileText, Clipboard, ClipboardList, Plus, CheckCircle, Clock,
  Package, ShoppingCart, X, Edit3
} from 'lucide-react';
import { QuoteSheetDialog, CalculationSheetDialog, PurchaseOrderDialog } from './QuoteDocumentDialogs';

// Card 컴포넌트
const Card = ({ title, children, className = '' }) => (
  <div className={`bg-white rounded-xl border border-gray-200 ${className}`}>
    {title && (
      <div className="px-6 py-4 border-b border-gray-200">
        {typeof title === 'string' ? (
          <h3 className="font-semibold text-gray-900">{title}</h3>
        ) : title}
      </div>
    )}
    <div className="p-6">{children}</div>
  </div>
);

// Button 컴포넌트
const Button = ({ children, variant = 'outline', size = 'md', onClick, disabled, className = '' }) => {
  const baseClasses = 'inline-flex items-center justify-center gap-2 font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed';
  const sizeClasses = size === 'sm' ? 'px-3 py-1.5 text-sm' : 'px-4 py-2';
  const variantClasses = variant === 'primary'
    ? 'bg-blue-600 text-white hover:bg-blue-700'
    : 'border border-gray-300 text-gray-700 hover:bg-gray-50';

  return (
    <button
      onClick={onClick}
      disabled={disabled}
      className={`${baseClasses} ${sizeClasses} ${variantClasses} ${className}`}
    >
      {children}
    </button>
  );
};

// StatusBadge 컴포넌트
const StatusBadge = ({ status }) => {
  const statusColors = {
    '최초작성': 'bg-gray-100 text-gray-700',
    '견적중': 'bg-yellow-100 text-yellow-700',
    '제출완료': 'bg-blue-100 text-blue-700',
    '확정': 'bg-indigo-100 text-indigo-700',
    '최종확정': 'bg-indigo-100 text-indigo-700',
    '수주전환': 'bg-green-100 text-green-700',
    '수정중': 'bg-yellow-100 text-yellow-700',
  };

  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${statusColors[status] || 'bg-gray-100 text-gray-700'}`}>
      {status}
    </span>
  );
};

// 견적 상세 컴포넌트
const QuoteDetailNew = ({
  quote,
  orders = [],
  onNavigate,
  onBack,
  onConvertToOrder,
  onUpdateQuote,
  onCreateOrder
}) => {
  // 문서 다이얼로그 상태
  const [showQuoteSheet, setShowQuoteSheet] = useState(false);
  const [showCalculationSheet, setShowCalculationSheet] = useState(false);
  const [showPurchaseOrder, setShowPurchaseOrder] = useState(false);
  const [showConvertModal, setShowConvertModal] = useState(false);
  const [showItemAddModal, setShowItemAddModal] = useState(false);

  const [newItem, setNewItem] = useState({
    category: '스크린',
    productName: '스크린 셔터 (표준형)',
    floor: '',
    location: '',
    width: '',
    height: '',
    qty: 1,
  });

  const [convertForm, setConvertForm] = useState({
    shipDate: '',
    shipDateUndecided: false,
    dueDate: '',
    dueDateUndecided: false,
    deliveryMethod: '상차',
    freightCost: '선불',
    receiverName: '',
    receiverPhone: '',
    postalCode: '',
    baseAddress: '',
    detailAddress: '',
    note: '',
  });

  // 연관 수주 찾기
  const relatedOrders = orders.filter(o => o.quoteId === quote.id || o.quoteNo === quote.quoteNo);

  // 수주된 품목 / 미수주 품목 분리
  const orderedItems = quote.items?.filter(item => item.orderStatus === 'ordered') || [];
  const pendingItems = quote.items?.filter(item => item.orderStatus !== 'ordered') || [];

  const handleConvertToOrder = () => {
    if (quote.status === '수주전환' && pendingItems.length === 0) {
      alert('모든 품목이 이미 수주로 전환되었습니다.');
      return;
    }
    setConvertForm({
      shipDate: '',
      shipDateUndecided: false,
      dueDate: '',
      dueDateUndecided: false,
      deliveryMethod: '상차',
      freightCost: '선불',
      receiverName: '',
      receiverPhone: '',
      postalCode: '',
      baseAddress: quote.deliveryAddress || '',
      detailAddress: '',
      note: '',
    });
    setShowConvertModal(true);
  };

  // 수주전환 실행
  const handleConvertConfirm = () => {
    const dateCode = new Date().toISOString().slice(2,10).replace(/-/g, '');
    const newOrderNo = `KD-SO-${dateCode}-${String(Math.floor(Math.random() * 100)).padStart(2, '0')}`;

    const newOrder = {
      id: Date.now(),
      orderNo: newOrderNo,
      quoteNo: quote.quoteNo,
      quoteId: quote.id,
      orderDate: new Date().toISOString().split('T')[0],
      customerName: quote.customerName,
      siteName: quote.siteName,
      siteAddress: convertForm.baseAddress ? `${convertForm.baseAddress} ${convertForm.detailAddress}`.trim() : quote.deliveryAddress,
      manager: quote.manager,
      contact: quote.contact,
      productName: quote.productName,
      qty: quote.qty,
      totalAmount: quote.finalAmount || quote.totalAmount,
      status: '수주확정',
      dueDate: convertForm.dueDateUndecided ? '미정' : convertForm.dueDate,
      shipDate: convertForm.shipDateUndecided ? '미정' : convertForm.shipDate,
      deliveryMethod: convertForm.deliveryMethod,
      freightCost: convertForm.freightCost,
      receiverName: convertForm.receiverName,
      receiverPhone: convertForm.receiverPhone,
      postalCode: convertForm.postalCode,
      deliveryAddress: convertForm.baseAddress,
      deliveryAddressDetail: convertForm.detailAddress,
      note: convertForm.note,
      creditGrade: quote.creditGrade,
      items: quote.items || [],
      history: [{
        id: Date.now(),
        changedAt: new Date().toISOString().replace('T', ' ').slice(0, 16),
        changeType: '수주등록',
        description: `견적(${quote.quoteNo})에서 수주전환`,
        changedBy: '현재 사용자',
      }],
    };

    if (onCreateOrder) {
      onCreateOrder(newOrder);
    }

    if (onUpdateQuote) {
      onUpdateQuote({
        ...quote,
        status: '수주전환',
        convertedOrderNo: newOrderNo,
      });
    }

    alert(`수주전환 완료!\n\n수주번호: ${newOrderNo}\n발주처: ${quote.customerName}\n현장: ${quote.siteName}\n금액: ${(quote.finalAmount || quote.totalAmount).toLocaleString()}원`);
    setShowConvertModal(false);
    onNavigate('order-list');
  };

  // 품목 추가
  const handleAddItem = () => {
    const unitPrice = newItem.category === '스크린'
      ? Math.round((newItem.width * newItem.height) / 1000 * 0.5)
      : 450000;
    const amount = unitPrice * newItem.qty;

    const addedItem = {
      id: Date.now(),
      ...newItem,
      width: parseInt(newItem.width) || 0,
      height: parseInt(newItem.height) || 0,
      unitPrice,
      amount,
      orderStatus: 'pending',
      orderId: null,
    };

    onUpdateQuote?.({
      ...quote,
      items: [...(quote.items || []), addedItem],
      totalAmount: (quote.totalAmount || 0) + amount,
    });

    setShowItemAddModal(false);
    setNewItem({
      category: '스크린',
      productName: '스크린 셔터 (표준형)',
      floor: '',
      location: '',
      width: '',
      height: '',
      qty: 1,
    });
  };

  return (
    <div className="space-y-6">
      {/* 헤더 영역 - 좌측: 타이틀+문서버튼 / 우측: 액션버튼 */}
      <div className="flex items-center justify-between">
        {/* 좌측: 타이틀 + 문서 버튼 */}
        <div className="flex items-center gap-4">
          <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
            <FileText className="w-6 h-6" />
            견적 상세
          </h1>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setShowQuoteSheet(true)}
              className="flex items-center gap-1 px-3 py-1.5 text-sm border border-gray-300 rounded hover:bg-gray-50 transition-colors"
            >
              <FileText className="w-4 h-4" />
              견적서
            </button>
            <button
              onClick={() => setShowCalculationSheet(true)}
              className="flex items-center gap-1 px-3 py-1.5 text-sm border border-gray-300 rounded hover:bg-gray-50 transition-colors"
            >
              <Clipboard className="w-4 h-4" />
              산출내역서
            </button>
            <button
              onClick={() => setShowPurchaseOrder(true)}
              className="flex items-center gap-1 px-3 py-1.5 text-sm border border-gray-300 rounded hover:bg-gray-50 transition-colors"
            >
              <ClipboardList className="w-4 h-4" />
              발주서
            </button>
          </div>
        </div>
        {/* 우측: 액션 버튼 */}
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={onBack}>
            목록
          </Button>
          <Button variant="outline" onClick={() => onNavigate('quote-edit', quote)}>
            <Edit3 className="w-4 h-4" />
            수정
          </Button>
          {/* 최종확정 버튼 - 최초작성/견적중/제출완료 상태에서만 표시 */}
          {['최초작성', '견적중', '제출완료'].includes(quote.status) && (
            <Button variant="primary" onClick={() => onUpdateQuote?.({ ...quote, status: '확정' })}>
              <CheckCircle className="w-4 h-4" />
              최종확정
            </Button>
          )}
          {/* 수주전환 버튼 - 확정/최종확정 상태에서만 표시 */}
          {['확정', '최종확정'].includes(quote.status) && (
            <Button variant="primary" onClick={handleConvertToOrder}>
              <ShoppingCart className="w-4 h-4" />
              수주전환
            </Button>
          )}
        </div>
      </div>

      {/* 기본 정보 */}
      <Card title="기본 정보">
        <div className="grid grid-cols-3 gap-6">
          <div>
            <label className="text-sm text-gray-500">견적번호</label>
            <p className="font-mono text-gray-900">{quote.quoteNo}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">작성자</label>
            <p className="text-gray-900">{quote.createdBy}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">발주처</label>
            <p className="text-gray-900">{quote.customerName}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">담당자</label>
            <p className="text-gray-900">{quote.manager}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">연락처</label>
            <p className="text-gray-900">{quote.contact}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">현장명</label>
            <p className="text-gray-900">{quote.siteName}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">현장코드</label>
            <p className="font-mono text-gray-900">{quote.siteCode}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">상태</label>
            <p><StatusBadge status={quote.status} /></p>
          </div>
          <div>
            <label className="text-sm text-gray-500">접수일</label>
            <p className="text-gray-900">{quote.quoteDate}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">납기일</label>
            <p className="text-gray-900">{quote.dueDate}</p>
          </div>
        </div>
        {quote.note && (
          <div className="mt-4 pt-4 border-t">
            <label className="text-sm text-gray-500">비고</label>
            <p className="text-gray-900">{quote.note}</p>
          </div>
        )}
      </Card>

      {/* 자동 견적 산출 정보 */}
      <Card title="자동 견적 산출 정보">
        <div className="grid grid-cols-3 gap-6">
          <div>
            <label className="text-sm text-gray-500">품목</label>
            <p className="text-gray-900">{quote.productName || '스크린 셔터'}</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">수량</label>
            <p className="text-gray-900">{quote.qty || 1}개</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">단가</label>
            <p className="text-gray-900">{quote.unitPrice?.toLocaleString() || '-'}원</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">공급가액</label>
            <p className="text-gray-900">{quote.totalAmount?.toLocaleString()}원</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">부가세</label>
            <p className="text-gray-900">{Math.round((quote.totalAmount || 0) * 0.1).toLocaleString()}원</p>
          </div>
          <div>
            <label className="text-sm text-gray-500">총 견적금액</label>
            <p className="text-xl font-bold text-blue-600">{Math.round((quote.totalAmount || 0) * 1.1).toLocaleString()}원</p>
          </div>
        </div>
      </Card>

      {/* 특이사항 */}
      <Card title="특이사항">
        <div className="min-h-[80px]">
          {quote.specialNote ? (
            <p className="text-gray-900">{quote.specialNote}</p>
          ) : (
            <p className="text-gray-400">등록된 특이사항이 없습니다.</p>
          )}
        </div>
      </Card>

      {/* 문서 다이얼로그들 */}
      {showQuoteSheet && (
        <QuoteSheetDialog quote={quote} onClose={() => setShowQuoteSheet(false)} />
      )}
      {showCalculationSheet && (
        <CalculationSheetDialog quote={quote} onClose={() => setShowCalculationSheet(false)} />
      )}
      {showPurchaseOrder && (
        <PurchaseOrderDialog quote={quote} onClose={() => setShowPurchaseOrder(false)} />
      )}

      {/* 수주전환 모달 */}
      {showConvertModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl shadow-2xl w-full max-w-lg mx-4">
            <div className="flex items-center justify-between p-4 border-b">
              <div>
                <h3 className="text-lg font-bold text-gray-900">수주전환</h3>
                <p className="text-sm text-gray-500 mt-0.5">배송 정보를 입력하여 수주로 전환합니다</p>
              </div>
              <button onClick={() => setShowConvertModal(false)} className="p-1 hover:bg-gray-100 rounded">
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-4 space-y-4 max-h-[70vh] overflow-y-auto">
              {/* 출고예정일 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">출고예정일</label>
                <div className="flex items-center gap-2">
                  <input
                    type="date"
                    value={convertForm.shipDate}
                    onChange={(e) => setConvertForm(prev => ({ ...prev, shipDate: e.target.value }))}
                    disabled={convertForm.shipDateUndecided}
                    placeholder="연도-월-일"
                    className="flex-1 px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
                  />
                  <label className="flex items-center gap-2 text-sm text-gray-600 whitespace-nowrap">
                    <input
                      type="checkbox"
                      checked={convertForm.shipDateUndecided}
                      onChange={(e) => setConvertForm(prev => ({ ...prev, shipDateUndecided: e.target.checked, shipDate: '' }))}
                      className="rounded border-gray-300"
                    />
                    미정
                  </label>
                </div>
              </div>

              {/* 납품요청일 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  납품요청일 <span className="text-red-500">*</span>
                </label>
                <div className="flex items-center gap-2">
                  <input
                    type="date"
                    value={convertForm.dueDate}
                    onChange={(e) => setConvertForm(prev => ({ ...prev, dueDate: e.target.value }))}
                    disabled={convertForm.dueDateUndecided}
                    placeholder="연도-월-일"
                    className="flex-1 px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100"
                  />
                  <label className="flex items-center gap-2 text-sm text-gray-600 whitespace-nowrap">
                    <input
                      type="checkbox"
                      checked={convertForm.dueDateUndecided}
                      onChange={(e) => setConvertForm(prev => ({ ...prev, dueDateUndecided: e.target.checked, dueDate: '' }))}
                      className="rounded border-gray-300"
                    />
                    미정
                  </label>
                </div>
              </div>

              {/* 배송방식 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">배송방식</label>
                <select
                  value={convertForm.deliveryMethod}
                  onChange={(e) => setConvertForm(prev => ({ ...prev, deliveryMethod: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 appearance-none bg-white"
                >
                  <option value="상차">상차</option>
                  <option value="택배">택배</option>
                  <option value="직접배송">직접배송</option>
                </select>
              </div>

              {/* 운임비용 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">운임비용</label>
                <select
                  value={convertForm.freightCost}
                  onChange={(e) => setConvertForm(prev => ({ ...prev, freightCost: e.target.value }))}
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 appearance-none bg-white"
                >
                  <option value="선불">선불</option>
                  <option value="착불">착불</option>
                  <option value="무료">무료</option>
                </select>
              </div>

              {/* 수령인 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  수령인 <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  value={convertForm.receiverName}
                  onChange={(e) => setConvertForm(prev => ({ ...prev, receiverName: e.target.value }))}
                  placeholder="수령인 이름"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* 연락처 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  연락처 <span className="text-red-500">*</span>
                </label>
                <input
                  type="tel"
                  value={convertForm.receiverPhone}
                  onChange={(e) => setConvertForm(prev => ({ ...prev, receiverPhone: e.target.value }))}
                  placeholder="010-0000-0000"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* 배송지 주소 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">배송지 주소</label>
                <div className="space-y-2">
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={convertForm.postalCode}
                      onChange={(e) => setConvertForm(prev => ({ ...prev, postalCode: e.target.value }))}
                      placeholder="우편번호"
                      className="flex-1 px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                      readOnly
                    />
                    <button
                      type="button"
                      onClick={() => alert('우편번호 검색 API 연동 필요')}
                      className="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 flex items-center gap-1 whitespace-nowrap"
                    >
                      <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                      </svg>
                      우편번호 찾기
                    </button>
                  </div>
                  <input
                    type="text"
                    value={convertForm.baseAddress}
                    onChange={(e) => setConvertForm(prev => ({ ...prev, baseAddress: e.target.value }))}
                    placeholder="기본 주소 (우편번호 검색 후 자동 입력됩니다)"
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    readOnly
                  />
                  <input
                    type="text"
                    value={convertForm.detailAddress}
                    onChange={(e) => setConvertForm(prev => ({ ...prev, detailAddress: e.target.value }))}
                    placeholder="상세 주소를 입력하세요"
                    className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                </div>
              </div>

              {/* 비고 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">비고</label>
                <input
                  type="text"
                  value={convertForm.note}
                  onChange={(e) => setConvertForm(prev => ({ ...prev, note: e.target.value }))}
                  placeholder="특이사항"
                  className="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>
            </div>

            <div className="flex gap-2 p-4 border-t bg-gray-50 rounded-b-xl">
              <Button variant="outline" className="flex-1" onClick={() => setShowConvertModal(false)}>
                취소
              </Button>
              <Button variant="primary" className="flex-1" onClick={handleConvertConfirm}>
                저장
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default QuoteDetailNew;
