// frontend/src/modals/crm/MailViewModal.jsx
// Full email reading modal — iframe body, dark/light toggle, attachments, add-customer banner.

import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import api from '@/lib/api'
import { fmtDateTimeFull } from '@/lib/formatters'

const MEDIA_CATEGORIES = [
  { value: 'received_media', label: 'Received Media' },
  { value: 'media',          label: 'General'         },
  { value: 'documents',      label: 'Documents'       },
  { value: 'invoices',       label: 'Invoices'        },
  { value: 'quotations',     label: 'Quotations'      },
  { value: 'sent_media',     label: 'Sent Media'      },
]

function fullDate(dateStr) { return fmtDateTimeFull(dateStr) }

// ─── Save Inline Image mini-modal ────────────────────────────────────────────

function SaveInlineModal({ image, commId, onClose }) {
  // image: { filename, mime_type, dataUri }
  const [filename, setFilename]   = useState(image.filename)
  const [subfolder, setSubfolder] = useState('received_media')
  const [saving, setSaving]       = useState(false)
  const [done, setDone]           = useState(false)
  const [err, setErr]             = useState('')

  const handleSave = async () => {
    if (!filename.trim()) { setErr('Please enter a filename.'); return }
    setSaving(true); setErr('')
    try {
      await api.post(`/crm/comms/email/${commId}/save-inline`, {
        data_uri:  image.dataUri,
        filename:  filename.trim(),
        subfolder,
        mime_type: image.mime_type,
      })
      setDone(true)
    } catch (e) {
      setErr(e.message)
    } finally {
      setSaving(false)
    }
  }

  const inputStyle = {
    width: '100%',
    padding: 'var(--space-2) var(--space-3)',
    fontSize: 'var(--font-size-sm)',
    backgroundColor: 'var(--color-bg-elevated)',
    border: '1px solid var(--color-border-strong)',
    borderRadius: 'var(--radius-md)',
    color: 'var(--color-text-primary)',
    outline: 'none',
    fontFamily: 'var(--font-family-base)',
  }

  return (
    <div
      style={{
        position: 'fixed', inset: 0, zIndex: 1300,
        backgroundColor: 'rgba(0,0,0,0.65)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}
      onClick={done ? onClose : undefined}
    >
      <div
        style={{
          backgroundColor: 'var(--color-bg-surface)',
          border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-xl)',
          padding: 'var(--space-6)',
          width: 400,
          boxShadow: 'var(--shadow-xl)',
        }}
        onClick={(e) => e.stopPropagation()}
      >
        {done ? (
          <div style={{ textAlign: 'center', padding: 'var(--space-4) 0' }}>
            <div style={{ fontSize: 32, marginBottom: 'var(--space-3)' }}>✓</div>
            <p style={{ color: 'var(--color-text-primary)', fontWeight: 'var(--font-weight-semibold)', marginBottom: 'var(--space-1)' }}>Saved successfully</p>
            <p style={{ color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)', marginBottom: 'var(--space-5)' }}>
              Stored in <strong>{MEDIA_CATEGORIES.find(c => c.value === subfolder)?.label ?? subfolder}</strong>
            </p>
            <Button variant="primary" size="sm" onClick={onClose}>Done</Button>
          </div>
        ) : (
          <>
            <h3 style={{ color: 'var(--color-text-primary)', fontWeight: 'var(--font-weight-semibold)', fontSize: 'var(--font-size-base)', marginBottom: 'var(--space-1)' }}>
              Save to Customer Media
            </h3>
            <p style={{ color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)', marginBottom: 'var(--space-4)' }}>
              This image will be saved to the customer's media folder in Nextcloud.
            </p>

            <div style={{ marginBottom: 'var(--space-3)' }}>
              <label style={{ display: 'block', fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)', marginBottom: 'var(--space-1)' }}>
                Filename
              </label>
              <input style={inputStyle} value={filename} onChange={(e) => setFilename(e.target.value)} autoFocus />
            </div>

            <div style={{ marginBottom: 'var(--space-5)' }}>
              <label style={{ display: 'block', fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)', marginBottom: 'var(--space-1)' }}>
                Media Type
              </label>
              <select
                style={inputStyle}
                value={subfolder}
                onChange={(e) => setSubfolder(e.target.value)}
              >
                {MEDIA_CATEGORIES.map((c) => (
                  <option key={c.value} value={c.value}>{c.label}</option>
                ))}
              </select>
            </div>

            {err && <p style={{ color: 'var(--color-danger)', fontSize: 'var(--font-size-sm)', marginBottom: 'var(--space-3)' }}>{err}</p>}

            <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-2)' }}>
              <Button variant="ghost" size="sm" onClick={onClose}>Cancel</Button>
              <Button variant="primary" size="sm" onClick={handleSave} loading={saving}>Save</Button>
            </div>
          </>
        )}
      </div>
    </div>
  )
}

// ─── Add Customer mini-modal ─────────────────────────────────────────────────

function AddCustomerModal({ email, onClose, onCreated }) {
  const [name, setName]                     = useState('')
  const [surname, setSurname]               = useState('')
  const [organization, setOrganization]     = useState('')
  const [saving, setSaving]                 = useState(false)
  const [err, setErr]                       = useState('')

  const handleSave = async () => {
    if (!name.trim()) { setErr('Please enter a first name.'); return }
    setSaving(true); setErr('')
    try {
      const data = await api.post('/crm/customers', {
        name: name.trim(),
        surname: surname.trim(),
        organization: organization.trim(),
        language: 'en',
        contacts: [{ type: 'email', label: 'Email', value: email, primary: true }],
      })
      onCreated(data)
    } catch (e) {
      setErr(e.message)
    } finally {
      setSaving(false)
    }
  }

  const inputStyle = {
    width: '100%',
    padding: 'var(--space-2) var(--space-3)',
    fontSize: 'var(--font-size-sm)',
    backgroundColor: 'var(--color-bg-elevated)',
    border: '1px solid var(--color-border-strong)',
    borderRadius: 'var(--radius-md)',
    color: 'var(--color-text-primary)',
    outline: 'none',
  }

  return (
    <div
      style={{
        position: 'fixed', inset: 0, zIndex: 1200,
        backgroundColor: 'rgba(0,0,0,0.6)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}
      onClick={onClose}
    >
      <div
        style={{
          backgroundColor: 'var(--color-bg-surface)',
          border: '1px solid var(--color-border)',
          borderRadius: 'var(--radius-xl)',
          padding: 'var(--space-6)',
          width: 420,
          boxShadow: 'var(--shadow-xl)',
        }}
        onClick={(e) => e.stopPropagation()}
      >
        <h3 style={{ color: 'var(--color-text-primary)', fontWeight: 'var(--font-weight-semibold)', fontSize: 'var(--font-size-base)', marginBottom: 'var(--space-1)' }}>
          Add Customer
        </h3>
        <p style={{ color: 'var(--color-text-muted)', fontSize: 'var(--font-size-sm)', marginBottom: 'var(--space-4)' }}>
          Adding <strong style={{ color: 'var(--color-text-accent)' }}>{email}</strong> as a new customer.
        </p>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)', marginBottom: 'var(--space-3)' }}>
          <div>
            <label style={{ display: 'block', fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)', marginBottom: 'var(--space-1)' }}>First Name *</label>
            <input style={inputStyle} value={name} onChange={(e) => setName(e.target.value)} placeholder="First name" autoFocus />
          </div>
          <div>
            <label style={{ display: 'block', fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)', marginBottom: 'var(--space-1)' }}>Last Name</label>
            <input style={inputStyle} value={surname} onChange={(e) => setSurname(e.target.value)} placeholder="Last name" />
          </div>
        </div>

        <div style={{ marginBottom: 'var(--space-3)' }}>
          <label style={{ display: 'block', fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)', marginBottom: 'var(--space-1)' }}>Organization</label>
          <input style={inputStyle} value={organization} onChange={(e) => setOrganization(e.target.value)} placeholder="Church, school, etc." />
        </div>

        <div style={{ marginBottom: 'var(--space-4)' }}>
          <label style={{ display: 'block', fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)', marginBottom: 'var(--space-1)' }}>Email</label>
          <input style={{ ...inputStyle, color: 'var(--color-text-muted)', cursor: 'not-allowed' }} value={email} readOnly />
        </div>

        {err && <p style={{ color: 'var(--color-danger)', fontSize: 'var(--font-size-sm)', marginBottom: 'var(--space-3)' }}>{err}</p>}

        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-2)' }}>
          <Button variant="ghost" size="sm" onClick={onClose}>Cancel</Button>
          <Button variant="primary" size="sm" onClick={handleSave} loading={saving}>Add Customer</Button>
        </div>
      </div>
    </div>
  )
}

// ─── Main modal ───────────────────────────────────────────────────────────────

export default function MailViewModal({ entry, customers, resolveCustomer, onClose, onReply }) {
  const [bodyLight, setBodyLight]             = useState(false)
  const [showAddCustomer, setShowAddCustomer] = useState(false)
  const [addedCustomer, setAddedCustomer]     = useState(null)
  const [inlineImages, setInlineImages]       = useState([])
  const [saveImage, setSaveImage]             = useState(null)   // image to save

  // Reset per-message state when entry changes
  useEffect(() => {
    setBodyLight(false)
    setAddedCustomer(null)
    setShowAddCustomer(false)
    setSaveImage(null)
  }, [entry])

  // Extract inline images from HTML body
  useEffect(() => {
    const html = entry?.body_html
    if (!html) { setInlineImages([]); return }
    const parser = new DOMParser()
    const doc = parser.parseFromString(html, 'text/html')
    const imgs = Array.from(doc.querySelectorAll('img[src^="data:"]'))
    setInlineImages(imgs.map((img, i) => {
      const src = img.getAttribute('src')
      const mimeMatch = src.match(/^data:([^;]+);/)
      const mime = mimeMatch ? mimeMatch[1] : 'image/png'
      const ext = mime.split('/')[1] || 'png'
      return { filename: `inline-image-${i + 1}.${ext}`, mime_type: mime }
    }))
  }, [entry])

  if (!entry) return null

  const customer = resolveCustomer
    ? resolveCustomer(entry)
    : (entry.customer_id ? customers?.[entry.customer_id] : null)

  const isInbound = entry.direction === 'inbound'
  const replyAddr = isInbound
    ? (entry.from_addr || '')
    : (Array.isArray(entry.to_addrs) ? entry.to_addrs[0] : entry.to_addrs || '')

  const toAddrs = Array.isArray(entry.to_addrs)
    ? entry.to_addrs.join(', ')
    : (entry.to_addrs || '')

  const attachments = Array.isArray(entry.attachments) ? entry.attachments : []
  const unknownSenderEmail = isInbound && !customer && !addedCustomer ? (entry.from_addr || null) : null

  // Prefer body_html (rich HTML from IMAP), fall back to plain body
  const iframeContent = entry.body_html
    ? entry.body_html
    : `<pre style="font-family:inherit;white-space:pre-wrap;margin:0">${(entry.body || '').replace(/</g, '&lt;')}</pre>`

  const iframeSrcDoc = `<!DOCTYPE html><html><head>
    <meta charset="utf-8">
    <style>
      html, body { margin: 0; padding: 0; background: ${bodyLight ? '#ffffff' : '#141414'}; color: ${bodyLight ? '#1a1a1a' : '#e0e0e0'}; }
      body { padding: 20px 24px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; font-size: 14px; line-height: 1.65; }
      img { max-width: 100%; height: auto; display: inline-block; }
      pre { white-space: pre-wrap; word-break: break-word; }
      a { color: ${bodyLight ? '#1d4ed8' : '#60a5fa'}; }
      blockquote { border-left: 3px solid ${bodyLight ? '#d1d5db' : '#404040'}; margin: 8px 0; padding-left: 12px; color: ${bodyLight ? '#6b7280' : '#9ca3af'}; }
      table { color: ${bodyLight ? '#1a1a1a' : '#e0e0e0'}; }
      * { box-sizing: border-box; }
    </style>
  </head><body>${iframeContent}</body></html>`

  return (
    <>
      {/*
        We use className="mail-view-modal" to override .modal-body so it doesn't
        scroll — only the iframe scrolls. The style tag below is injected once.
      */}
      <style>{`
        .mail-view-modal .modal-body {
          overflow: hidden;
          display: flex;
          flex-direction: column;
          padding: 0;
        }
        .mail-view-modal .modal-header {
          border-bottom: none;
          padding-bottom: var(--space-3);
        }
      `}</style>

      <Modal
        open={!!entry}
        onClose={onClose}
        title={entry.subject || '(no subject)'}
        size="full"
        className="mail-view-modal"
        footer={
          <div style={{ display: 'flex', gap: 'var(--space-3)' }}>
            {replyAddr && (
              <Button variant="primary" size="sm" onClick={() => onReply(replyAddr, entry.mailbox_account)}>
                Reply
              </Button>
            )}
            <Button variant="ghost" size="sm" onClick={onClose}>Close</Button>
          </div>
        }
      >

        {/* ── Meta row (inline From / To / Date) — fixed ────────────── */}
        <div style={{
          display: 'flex', alignItems: 'center', flexWrap: 'wrap',
          gap: 'var(--space-1) var(--space-5)',
          padding: 'var(--space-2) var(--space-6) var(--space-3)',
          fontSize: 'var(--font-size-sm)',
          flexShrink: 0,
          borderBottom: '1px solid var(--color-border)',
        }}>
          {/* From */}
          <span style={{ color: 'var(--color-text-muted)' }}>
            From{' '}
            {customer ? (
              <Link
                to={`/crm/customers/${customer.id}`}
                onClick={onClose}
                style={{ color: 'var(--color-text-accent)', textDecoration: 'none', fontWeight: 'var(--font-weight-medium)' }}
              >
                {customer.name}{customer.surname ? ` ${customer.surname}` : ''}
                {customer.organization ? ` · ${customer.organization}` : ''}
              </Link>
            ) : null}
            {entry.from_addr && (
              <span style={{ color: 'var(--color-text-primary)', marginLeft: customer ? 'var(--space-1)' : 0 }}>
                {customer ? `<${entry.from_addr}>` : entry.from_addr}
              </span>
            )}
          </span>

          {/* Separator */}
          {toAddrs && <span style={{ color: 'var(--color-border-strong)' }}>·</span>}

          {/* To */}
          {toAddrs && (
            <span style={{ color: 'var(--color-text-muted)' }}>
              To <span style={{ color: 'var(--color-text-primary)' }}>{toAddrs}</span>
            </span>
          )}

          {/* Separator */}
          {entry.occurred_at && <span style={{ color: 'var(--color-border-strong)' }}>·</span>}

          {/* Date */}
          {entry.occurred_at && (
            <span style={{ color: 'var(--color-text-muted)' }}>
              {fullDate(entry.occurred_at)}
            </span>
          )}
        </div>

        {/* ── Body — flex:1, only this scrolls (via iframe) ─────────── */}
        <div style={{ flex: 1, position: 'relative', minHeight: 0 }}>
          {/* Dark / Light toggle */}
          <div style={{ position: 'absolute', top: 10, right: 16, zIndex: 10 }}>
            <button
              type="button"
              onClick={() => setBodyLight((v) => !v)}
              title={bodyLight ? 'Switch to dark mode' : 'Switch to light mode (better for images)'}
              style={{
                padding: '3px 10px',
                fontSize: 'var(--font-size-xs)',
                borderRadius: 'var(--radius-md)',
                cursor: 'pointer',
                border: '1px solid rgba(128,128,128,0.35)',
                backgroundColor: bodyLight ? 'rgba(255,255,255,0.85)' : 'rgba(0,0,0,0.55)',
                color: bodyLight ? '#333' : '#e0e0e0',
                backdropFilter: 'blur(4px)',
                transition: 'all 0.15s',
                lineHeight: 1.5,
              }}
            >
              {bodyLight ? '🌙 Dark' : '☀ Light'}
            </button>
          </div>

          <iframe
            sandbox="allow-same-origin allow-popups"
            referrerPolicy="no-referrer"
            style={{ width: '100%', height: '100%', border: 'none', display: 'block' }}
            srcDoc={iframeSrcDoc}
          />
        </div>

        {/* ── Inline images — fixed ─────────────────────────────────── */}
        {inlineImages.length > 0 && (
          <div style={{
            display: 'flex', alignItems: 'center', flexWrap: 'wrap',
            gap: 'var(--space-2)',
            padding: 'var(--space-2) var(--space-6)',
            borderTop: '1px solid var(--color-border)',
            backgroundColor: 'var(--color-bg-void)',
            flexShrink: 0,
          }}>
            <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-muted)', flexShrink: 0 }}>
              Inline Images
            </span>
            {inlineImages.map((img, i) => {
              const canSave = !!customer
              return (
                <button
                  key={i}
                  type="button"
                  onClick={canSave ? () => setSaveImage(img) : undefined}
                  title={canSave ? 'Click to save to customer media folder' : 'Not linked to a customer'}
                  style={{
                    display: 'flex', alignItems: 'center', gap: 'var(--space-1)',
                    padding: '2px var(--space-3)',
                    backgroundColor: 'var(--color-bg-elevated)',
                    border: '1px solid var(--color-border)',
                    borderRadius: 'var(--radius-md)',
                    fontSize: 'var(--font-size-xs)',
                    color: 'var(--color-text-primary)',
                    cursor: canSave ? 'pointer' : 'default',
                    transition: 'border-color 0.12s, background-color 0.12s',
                    fontFamily: 'var(--font-family-base)',
                  }}
                  onMouseEnter={canSave ? (e) => { e.currentTarget.style.borderColor = 'var(--color-primary)'; e.currentTarget.style.backgroundColor = 'var(--color-primary-subtle)' } : undefined}
                  onMouseLeave={canSave ? (e) => { e.currentTarget.style.borderColor = 'var(--color-border)'; e.currentTarget.style.backgroundColor = 'var(--color-bg-elevated)' } : undefined}
                >
                  <span>🖼</span>
                  <span style={{ maxWidth: 180, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{img.filename}</span>
                  {canSave && <span style={{ color: 'var(--color-text-muted)', marginLeft: 2 }}>↓</span>}
                </button>
              )
            })}
            {!customer && (
              <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)', fontStyle: 'italic' }}>
                Link to a customer to save images
              </span>
            )}
          </div>
        )}

        {/* ── Attachments — fixed ───────────────────────────────────── */}
        {attachments.length > 0 && (
          <div style={{
            display: 'flex', alignItems: 'center', flexWrap: 'wrap',
            gap: 'var(--space-2)',
            padding: 'var(--space-2) var(--space-6)',
            borderTop: '1px solid var(--color-border)',
            backgroundColor: 'var(--color-bg-void)',
            flexShrink: 0,
          }}>
            <span style={{ fontSize: 'var(--font-size-xs)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-muted)', flexShrink: 0 }}>
              Attachments
            </span>
            {attachments.map((a, i) => {
              const name = a.filename || a.name || 'file'
              const ct = a.content_type || ''
              const kb = a.size ? ` · ${Math.ceil(a.size / 1024)} KB` : ''
              const icon = ct.startsWith('image/') ? '🖼' : ct === 'application/pdf' ? '📑' : ct.startsWith('video/') ? '🎬' : '📎'
              return (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 'var(--space-1)',
                  padding: '2px var(--space-3)',
                  backgroundColor: 'var(--color-bg-elevated)',
                  border: '1px solid var(--color-border)',
                  borderRadius: 'var(--radius-md)',
                  fontSize: 'var(--font-size-xs)',
                  color: 'var(--color-text-primary)',
                }}>
                  <span>{icon}</span>
                  <span style={{ maxWidth: 220, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{name}{kb}</span>
                </div>
              )
            })}
          </div>
        )}

        {/* ── Unknown sender banner — fixed ────────────────────────── */}
        {unknownSenderEmail && (
          <div style={{
            padding: 'var(--space-2) var(--space-6)',
            borderTop: '1px solid var(--color-border)',
            backgroundColor: 'color-mix(in srgb, var(--color-warning) 8%, var(--color-bg-void))',
            fontSize: 'var(--font-size-sm)',
            color: 'var(--color-text-secondary)',
            flexShrink: 0,
          }}>
            <strong style={{ color: 'var(--color-text-primary)' }}>{unknownSenderEmail}</strong>
            {' '}is not in your Customer&apos;s list.{' '}
            <button
              type="button"
              onClick={() => setShowAddCustomer(true)}
              style={{
                background: 'none', border: 'none', padding: 0,
                color: 'var(--color-text-accent)',
                fontWeight: 'var(--font-weight-medium)',
                fontSize: 'inherit',
                cursor: 'pointer',
                textDecoration: 'underline',
              }}
            >
              Click here to add them.
            </button>
          </div>
        )}

        {/* ── Added-customer confirmation — fixed ───────────────────── */}
        {addedCustomer && (
          <div style={{
            padding: 'var(--space-2) var(--space-6)',
            borderTop: '1px solid var(--color-border)',
            backgroundColor: 'color-mix(in srgb, var(--color-success) 8%, var(--color-bg-void))',
            fontSize: 'var(--font-size-sm)',
            color: 'var(--color-text-secondary)',
            flexShrink: 0,
          }}>
            ✓ <strong style={{ color: 'var(--color-text-primary)' }}>{addedCustomer.name}</strong> has been added as a customer.
          </div>
        )}

      </Modal>

      {/* Save inline image sub-modal */}
      {saveImage && entry && (
        <SaveInlineModal
          image={saveImage}
          commId={entry.id}
          onClose={() => setSaveImage(null)}
        />
      )}

      {/* Add Customer sub-modal */}
      {showAddCustomer && entry?.from_addr && (
        <AddCustomerModal
          email={entry.from_addr}
          onClose={() => setShowAddCustomer(false)}
          onCreated={(newCustomer) => {
            setAddedCustomer(newCustomer)
            setShowAddCustomer(false)
          }}
        />
      )}
    </>
  )
}
