'use client';

import React, { useEffect, useState } from 'react';

interface QuotationViewerClientProps {
  record: any;
  isExpired: boolean;
}

export default function QuotationViewerClient({ record, isExpired }: QuotationViewerClientProps) {
  const [isBlurred, setIsBlurred] = useState(false);

  const security = record?.securityOptions || {};
  const preventPrint = security.preventPrint !== false;
  const preventCopy = security.preventCopy !== false;
  const blurOnLoss = security.blurOnLoss !== false;
  const enableWatermark = security.enableWatermark !== false;

  useEffect(() => {
    if (isExpired) return;

    const handleContextMenu = (e: MouseEvent) => {
      if (preventCopy) e.preventDefault();
    };

    const handleSelectStart = (e: Event) => {
      if (preventCopy) e.preventDefault();
    };

    const handleDragStart = (e: Event) => {
      if (preventCopy) e.preventDefault();
    };

    const handleKeyDown = (e: KeyboardEvent) => {
      if (!preventCopy) return;
      if (e.ctrlKey && ['p', 's', 'c', 'u'].includes(e.key.toLowerCase())) {
        e.preventDefault();
      }
      if (e.key === 'F12' || (e.ctrlKey && e.shiftKey && e.key === 'I')) {
        e.preventDefault();
      }
    };

    const handleBlur = () => {
      if (blurOnLoss) setIsBlurred(true);
    };

    const handleFocus = () => {
      if (blurOnLoss) setIsBlurred(false);
    };

    if (preventCopy) {
      document.addEventListener('contextmenu', handleContextMenu);
      document.addEventListener('selectstart', handleSelectStart);
      document.addEventListener('dragstart', handleDragStart);
      document.addEventListener('keydown', handleKeyDown);
    }

    if (blurOnLoss) {
      window.addEventListener('blur', handleBlur);
      window.addEventListener('focus', handleFocus);
    }

    return () => {
      if (preventCopy) {
        document.removeEventListener('contextmenu', handleContextMenu);
        document.removeEventListener('selectstart', handleSelectStart);
        document.removeEventListener('dragstart', handleDragStart);
        document.removeEventListener('keydown', handleKeyDown);
      }
      if (blurOnLoss) {
        window.removeEventListener('blur', handleBlur);
        window.removeEventListener('focus', handleFocus);
      }
    };
  }, [preventCopy, blurOnLoss, isExpired]);

  if (isExpired) {
    return (
      <div style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#f8f9fa',
        padding: '20px',
        fontFamily: 'sans-serif'
      }}>
        <div style={{
          maxWidth: '480px',
          width: '100%',
          backgroundColor: '#ffffff',
          borderRadius: '12px',
          padding: '32px 24px',
          boxShadow: '0 8px 30px rgba(0,0,0,0.08)',
          textAlign: 'center',
          borderTop: '5px solid #e03131'
        }}>
          <div style={{ fontSize: '48px', marginBottom: '12px' }}>🔒</div>
          <h2 style={{ fontSize: '20px', fontWeight: 700, color: '#e03131', marginBottom: '10px' }}>
            유효기간이 만료된 견적서입니다
          </h2>
          <p style={{ fontSize: '14px', color: '#495057', lineHeight: 1.6, marginBottom: '20px' }}>
            본 견적서({record?.quoteNo})는 지정된 유효기간이 지났습니다.<br />
            보안 정책에 따라 열람이 차단되었습니다.
          </p>
          <div style={{ fontSize: '12px', color: '#868e96', backgroundColor: '#f1f3f5', padding: '10px', borderRadius: '6px' }}>
            필요시 작성자({record?.companyInfo?.name || '재활공학연구소'})에게 재발행을 요청해 주세요.
          </div>
        </div>
      </div>
    );
  }

  const items = record?.items || [];
  const supplyTotal = items.reduce((sum: number, i: any) => sum + (Number(i.supplyAmount) || 0), 0);
  const vatTotal = items.reduce((sum: number, i: any) => sum + (Number(i.vat) || 0), 0);
  const grandTotal = supplyTotal + vatTotal;

  const watermarkText = `${record?.customerName || '고객'} | ${record?.quoteNo} | ${record?.quoteDate} 보안발행`;
  const watermarkBg = enableWatermark ? `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='320' height='220'><text x='20' y='120' fill='rgba(220,53,69,0.06)' font-size='14' font-family='sans-serif' transform='rotate(-25 160 110)'>${encodeURIComponent(watermarkText)}</text></svg>")` : 'none';

  const expiryDateStr = new Date(record?.expiresAt || Date.now()).toISOString().slice(0, 10);

  return (
    <div style={{
      minHeight: '100vh',
      backgroundColor: '#f8f9fa',
      color: '#212529',
      padding: '30px 15px',
      lineHeight: 1.5,
      fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
      backgroundImage: watermarkBg,
      backgroundRepeat: 'repeat',
      userSelect: preventCopy ? 'none' : 'auto'
    }}>
      <style jsx global>{`
        ${preventPrint ? '@media print { body { display: none !important; } }' : ''}
      `}</style>

      <div style={{
        maxWidth: '800px',
        margin: '0 auto',
        backgroundColor: '#ffffff',
        borderRadius: '10px',
        boxShadow: '0 4px 20px rgba(0,0,0,0.08)',
        padding: '35px 40px',
        position: 'relative',
        filter: isBlurred ? 'blur(25px)' : 'none',
        transition: 'filter 0.2s ease'
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '30px', paddingBottom: '20px', borderBottom: '2px solid #339af0' }}>
          <div>
            <div style={{ fontSize: '26px', fontWeight: 800, color: '#1c7ed6', letterSpacing: '-0.5px' }}>
              견 적 서 (Quotation)
            </div>
            <div style={{ fontSize: '12px', color: '#868e96', marginTop: '4px' }}>
              견적번호: {record?.quoteNo}
            </div>
          </div>
          <div style={{ fontSize: '13px', color: '#495057', textAlign: 'right', lineHeight: 1.6 }}>
            <div>발행일자: <strong>{record?.quoteDate}</strong></div>
            <div>유효기간: <strong>{expiryDateStr} 까지</strong></div>
          </div>
        </div>

        <div style={{ display: 'flex', gap: '20px', marginBottom: '30px' }}>
          <div style={{ flex: 1, backgroundColor: '#f1f3f5', borderRadius: '8px', padding: '18px', fontSize: '13px', borderLeft: '4px solid #339af0' }}>
            <h3 style={{ fontSize: '14px', marginBottom: '8px', color: '#1c7ed6' }}>[ 수 신 ]</h3>
            <p style={{ fontSize: '16px', fontWeight: 700, color: '#212529' }}>{record?.customerName || '귀하'}</p>
            <p style={{ marginTop: '6px', color: '#868e96' }}>아래와 같이 견적합니다.</p>
          </div>
          <div style={{ flex: 1, backgroundColor: '#f1f3f5', borderRadius: '8px', padding: '18px', fontSize: '13px', borderLeft: '4px solid #495057' }}>
            <h3 style={{ fontSize: '14px', marginBottom: '8px', color: '#1c7ed6' }}>[ 공급자 ]</h3>
            <p style={{ marginBottom: '4px', color: '#495057' }}><strong>상호:</strong> {record?.companyInfo?.name || '재활공학연구소'}</p>
            <p style={{ marginBottom: '4px', color: '#495057' }}><strong>사업자번호:</strong> {record?.companyInfo?.bizNum || '-'}</p>
            <p style={{ marginBottom: '4px', color: '#495057' }}><strong>대표자:</strong> {record?.companyInfo?.owner || '-'}</p>
            <p style={{ marginBottom: '4px', color: '#495057' }}><strong>연락처:</strong> {record?.companyInfo?.phone || '-'}</p>
          </div>
        </div>

        <table style={{ width: '100%', borderCollapse: 'collapse', marginBottom: '25px', fontSize: '13px' }}>
          <thead>
            <tr>
              <th style={{ backgroundColor: '#e7f5ff', color: '#1c7ed6', fontWeight: 700, padding: '10px 12px', borderBottom: '2px solid #a5d8ff', textAlign: 'center', width: '40px' }}>#</th>
              <th style={{ backgroundColor: '#e7f5ff', color: '#1c7ed6', fontWeight: 700, padding: '10px 12px', borderBottom: '2px solid #a5d8ff', textAlign: 'left' }}>품명 및 규격</th>
              <th style={{ backgroundColor: '#e7f5ff', color: '#1c7ed6', fontWeight: 700, padding: '10px 12px', borderBottom: '2px solid #a5d8ff', textAlign: 'center', width: '70px' }}>규격</th>
              <th style={{ backgroundColor: '#e7f5ff', color: '#1c7ed6', fontWeight: 700, padding: '10px 12px', borderBottom: '2px solid #a5d8ff', textAlign: 'right', width: '50px' }}>수량</th>
              <th style={{ backgroundColor: '#e7f5ff', color: '#1c7ed6', fontWeight: 700, padding: '10px 12px', borderBottom: '2px solid #a5d8ff', textAlign: 'right', width: '100px' }}>단가</th>
              <th style={{ backgroundColor: '#e7f5ff', color: '#1c7ed6', fontWeight: 700, padding: '10px 12px', borderBottom: '2px solid #a5d8ff', textAlign: 'right', width: '110px' }}>공급가액</th>
              <th style={{ backgroundColor: '#e7f5ff', color: '#1c7ed6', fontWeight: 700, padding: '10px 12px', borderBottom: '2px solid #a5d8ff', textAlign: 'right', width: '90px' }}>부가세</th>
            </tr>
          </thead>
          <tbody>
            {items.map((item: any, idx: number) => (
              <tr key={idx}>
                <td style={{ padding: '10px 12px', borderBottom: '1px solid #e9ecef', textAlign: 'center', color: '#6c757d' }}>{idx + 1}</td>
                <td style={{ padding: '10px 12px', borderBottom: '1px solid #e9ecef', fontWeight: 600, color: '#212529' }}>
                  {item.name}
                  {item.productCode && <div style={{ fontSize: '0.82em', color: '#868e96', fontWeight: 'normal' }}>코드: {item.productCode}</div>}
                </td>
                <td style={{ padding: '10px 12px', borderBottom: '1px solid #e9ecef', textAlign: 'center', color: '#495057' }}>{item.size || '-'}</td>
                <td style={{ padding: '10px 12px', borderBottom: '1px solid #e9ecef', textAlign: 'right', color: '#495057' }}>{(Number(item.qty) || 1).toLocaleString()}</td>
                <td style={{ padding: '10px 12px', borderBottom: '1px solid #e9ecef', textAlign: 'right', color: '#495057' }}>{(Number(item.unitPrice) || 0).toLocaleString()}원</td>
                <td style={{ padding: '10px 12px', borderBottom: '1px solid #e9ecef', textAlign: 'right', fontWeight: 600, color: '#212529' }}>{(Number(item.supplyAmount) || 0).toLocaleString()}원</td>
                <td style={{ padding: '10px 12px', borderBottom: '1px solid #e9ecef', textAlign: 'right', color: '#868e96', fontSize: '0.88em' }}>{(Number(item.vat) || 0).toLocaleString()}원</td>
              </tr>
            ))}
          </tbody>
        </table>

        <div style={{ backgroundColor: '#e7f5ff', borderRadius: '8px', padding: '18px', marginBottom: '25px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: '15px', fontWeight: 700, color: '#1c7ed6' }}>총 견적금액 (공급가액 + 부가세)</div>
            <div style={{ fontSize: '12px', color: '#495057', marginTop: '2px' }}>(공급가액: {supplyTotal.toLocaleString()}원 / 부가세: {vatTotal.toLocaleString()}원)</div>
          </div>
          <div style={{ fontSize: '22px', fontWeight: 900, color: '#1864ab' }}>₩ {grandTotal.toLocaleString()} 원</div>
        </div>

        <div style={{ fontSize: '12px', color: '#868e96', borderTop: '1px solid #dee2e6', paddingTop: '15px' }}>
          <p><strong>입금계좌:</strong> {record?.companyInfo?.bank || '-'}</p>
          <p style={{ marginTop: '4px' }}>{record?.note || ''}</p>
        </div>
      </div>
    </div>
  );
}
