// frontend/src/modals/crm/PdfViewModal.jsx
// Fullscreen PDF viewer for quotations — used from both QuotationList and QuotationForm

import { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
import Button from '@/components/ui/Button'
import Spinner from '@/components/ui/Spinner'

export default function PdfViewModal({ open, quotationId, quotationNumber, onClose }) {
  const [blobUrl, setBlobUrl] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)

  useEffect(() => {
    if (!open || !quotationId) return
    setBlobUrl(null)
    setLoading(true)
    setError(false)
    let objectUrl = null
    const token = localStorage.getItem('access_token')
    fetch(`/api/crm/quotations/${quotationId}/pdf`, {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
    })
      .then(r => {
        if (!r.ok) throw new Error('Failed to load PDF')
        return r.blob()
      })
      .then(blob => {
        objectUrl = URL.createObjectURL(blob)
        setBlobUrl(objectUrl)
      })
      .catch(() => setError(true))
      .finally(() => setLoading(false))

    return () => { if (objectUrl) URL.revokeObjectURL(objectUrl) }
  }, [quotationId])

  useEffect(() => {
    if (!open) return
    function onKey(e) { if (e.key === 'Escape') onClose() }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [open, onClose])

  if (!open) return null

  return createPortal(
    <div
      onClick={onClose}
      style={{
        position: 'fixed',
        inset: 0,
        zIndex: 9999,
        backgroundColor: 'rgba(10,14,20,0.92)',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <div
        onClick={e => e.stopPropagation()}
        style={{
          backgroundColor: 'var(--color-bg-surface)',
          borderRadius: 'var(--radius-xl)',
          overflow: 'hidden',
          width: 'min(82vw, 1100px)',
          height: '88vh',
          display: 'flex',
          flexDirection: 'column',
          boxShadow: 'var(--shadow-lg)',
          border: '1px solid var(--color-border)',
        }}
      >
        {/* Header */}
        <div style={{
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          padding: 'var(--space-3) var(--space-4)',
          borderBottom: '1px solid var(--color-border)',
          flexShrink: 0,
          backgroundColor: 'var(--color-bg-void)',
        }}>
          <span style={{
            fontFamily: 'var(--font-family-mono)',
            fontSize: 'var(--font-size-sm)',
            fontWeight: 'var(--font-weight-semibold)',
            color: 'var(--color-text-primary)',
          }}>
            {quotationNumber}
          </span>
          <div style={{ display: 'flex', gap: 'var(--space-2)', alignItems: 'center' }}>
            {blobUrl && (
              <Button
                as="a"
                variant="secondary"
                size="sm"
                href={blobUrl}
                download={`${quotationNumber}.pdf`}
              >
                Download PDF
              </Button>
            )}
            <button
              onClick={onClose}
              aria-label="Close"
              style={{
                background: 'none',
                border: 'none',
                color: 'var(--color-text-muted)',
                fontSize: 22,
                cursor: 'pointer',
                lineHeight: 1,
                padding: '0 var(--space-1)',
                display: 'flex',
                alignItems: 'center',
              }}
            >
              <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                <path d="M4 4l10 10M14 4L4 14" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" />
              </svg>
            </button>
          </div>
        </div>

        {/* Body */}
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
          {loading && <Spinner size="lg" />}
          {error && (
            <span style={{ color: 'var(--color-danger)', fontSize: 'var(--font-size-sm)' }}>
              Failed to load PDF.
            </span>
          )}
          {blobUrl && (
            <iframe
              src={blobUrl}
              style={{ width: '100%', height: '100%', border: 'none', display: 'block' }}
              title={quotationNumber}
            />
          )}
        </div>
      </div>
    </div>,
    document.body,
  )
}
