// frontend/src/modals/crm/MailSettingsModal.jsx
// Mail settings: auto-refresh interval + email signature editor (Quill rich text).

import { useState, useEffect, useRef } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import { loadQuill } from '@/lib/loadQuill'

const DEFAULT_POLL_INTERVAL = 30

function getPollInterval() {
  const v = parseInt(localStorage.getItem('mail_poll_interval'), 10)
  return !isNaN(v) && v >= 15 && v <= 300 ? v : DEFAULT_POLL_INTERVAL
}

export default function MailSettingsModal({ open, onClose, onSaved }) {
  const [pollInterval, setPollInterval] = useState(String(getPollInterval()))
  const [saved, setSaved]               = useState(false)

  const editorRef  = useRef(null)
  const quillRef   = useRef(null)
  const [quillReady, setQuillReady] = useState(() => !!window.Quill)

  // Reset poll interval from storage each time modal opens
  useEffect(() => {
    if (open) {
      setPollInterval(String(getPollInterval()))
      setSaved(false)
    }
  }, [open])

  // Load Quill via shared loader (no-op if already loaded)
  useEffect(() => {
    if (!open) return
    loadQuill(() => setQuillReady(true))
  }, [open])

  // Mount Quill into the editor div after it's ready and modal is open
  useEffect(() => {
    if (!open || !quillReady || !editorRef.current || quillRef.current) return
    const q = new window.Quill(editorRef.current, {
      theme: 'snow',
      placeholder: 'Type your signature here…',
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline'],
          [{ color: [] }],
          ['link'],
          ['clean'],
        ],
      },
    })
    const stored = localStorage.getItem('mail_signature') || ''
    if (stored) q.clipboard.dangerouslyPasteHTML(stored)
    quillRef.current = q
  }, [open, quillReady])

  // Destroy Quill instance when modal closes
  useEffect(() => {
    if (!open) { quillRef.current = null }
  }, [open])

  const handleSave = () => {
    const html     = quillRef.current ? quillRef.current.root.innerHTML : ''
    const interval = Math.min(300, Math.max(15, parseInt(pollInterval, 10) || DEFAULT_POLL_INTERVAL))
    localStorage.setItem('mail_signature',    html)
    localStorage.setItem('mail_poll_interval', String(interval))
    setSaved(true)
    setTimeout(() => {
      setSaved(false)
      onSaved?.()
      onClose()
    }, 700)
  }

  return (
    <>
      {/* Quill dark-theme overrides — scoped to modal body */}
      <style>{`
        .mail-sig-quill .ql-toolbar {
          background: var(--color-bg-elevated);
          border-color: var(--color-border-strong) !important;
          border-bottom-color: var(--color-border) !important;
          border-top: none !important;
          border-left: none !important;
          border-right: none !important;
        }
        .mail-sig-quill .ql-toolbar button,
        .mail-sig-quill .ql-toolbar .ql-picker-label {
          color: var(--color-text-secondary) !important;
        }
        .mail-sig-quill .ql-toolbar .ql-stroke {
          stroke: var(--color-text-secondary) !important;
        }
        .mail-sig-quill .ql-toolbar button:hover .ql-stroke,
        .mail-sig-quill .ql-toolbar button.ql-active .ql-stroke {
          stroke: var(--color-primary) !important;
        }
        .mail-sig-quill .ql-toolbar .ql-fill {
          fill: var(--color-text-secondary) !important;
        }
        .mail-sig-quill .ql-toolbar button:hover .ql-fill,
        .mail-sig-quill .ql-toolbar button.ql-active .ql-fill {
          fill: var(--color-primary) !important;
        }
        .mail-sig-quill .ql-container {
          border: none !important;
        }
        .mail-sig-quill .ql-editor {
          color: var(--color-text-primary) !important;
          background: var(--color-bg-abyss) !important;
          min-height: 160px;
          font-family: var(--font-family-base) !important;
          font-size: var(--font-size-base) !important;
        }
        .mail-sig-quill .ql-editor.ql-blank::before {
          color: var(--color-text-muted) !important;
          font-style: normal !important;
        }
        .mail-sig-quill .ql-picker-options {
          background: var(--color-bg-elevated) !important;
          border-color: var(--color-border-strong) !important;
        }
      `}</style>

      <Modal
        open={open}
        onClose={onClose}
        title="Mail Settings"
        size="md"
        footer={
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', justifyContent: 'flex-end' }}>
            {saved && (
              <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-success)' }}>
                Saved!
              </span>
            )}
            <Button variant="secondary" size="md" onClick={onClose}>Cancel</Button>
            <Button variant="primary" size="md" onClick={handleSave}>Save settings</Button>
          </div>
        }
      >
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>

          {/* ── Auto-refresh interval ── */}
          <div>
            <div style={{ marginBottom: 'var(--space-3)' }}>
              <p style={{
                fontSize: 'var(--font-size-xs)',
                fontWeight: 'var(--font-weight-semibold)',
                textTransform: 'uppercase',
                letterSpacing: 'var(--tracking-wide)',
                color: 'var(--color-text-secondary)',
                margin: 0,
              }}>
                Auto-check interval
              </p>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
              <div style={{ width: 110 }}>
                <FormField
                  label=""
                  name="poll_interval"
                  type="number"
                  value={pollInterval}
                  onChange={(e) => setPollInterval(e.target.value)}
                  inputProps={{ min: 15, max: 300 }}
                />
              </div>
              <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
                seconds&ensp;<span style={{ fontSize: 'var(--font-size-xs)' }}>(min 15 · max 300)</span>
              </span>
            </div>
            <p style={{ margin: 'var(--space-2) 0 0', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
              How often the mailbox silently checks for new emails. A banner appears when new mail is detected.
            </p>
          </div>

          {/* ── Divider ── */}
          <div style={{ height: 1, backgroundColor: 'var(--color-border)' }} />

          {/* ── Email signature ── */}
          <div>
            <p style={{
              fontSize: 'var(--font-size-xs)',
              fontWeight: 'var(--font-weight-semibold)',
              textTransform: 'uppercase',
              letterSpacing: 'var(--tracking-wide)',
              color: 'var(--color-text-secondary)',
              margin: '0 0 var(--space-3)',
            }}>
              Email signature
            </p>
            <p style={{ margin: '0 0 var(--space-3)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
              Added to outgoing emails when you click "Add Signature" in the compose window.
            </p>

            <div
              className="mail-sig-quill"
              style={{
                border: '1px solid var(--color-border)',
                borderRadius: 'var(--radius-md)',
                overflow: 'hidden',
              }}
            >
              {quillReady ? (
                <div ref={editorRef} />
              ) : (
                <div style={{
                  minHeight: 160,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: 'var(--color-text-muted)',
                  fontSize: 'var(--font-size-sm)',
                  backgroundColor: 'var(--color-bg-abyss)',
                }}>
                  Loading editor…
                </div>
              )}
            </div>
          </div>

        </div>
      </Modal>
    </>
  )
}
