import { useState, useEffect, useMemo } from 'react'
import { getWhatsAppTemplates, deleteWhatsAppTemplate } from '../api/api'
import './WhatsAppInviteModal.css'

// ── Known system parameter keys → field definitions ─────────────────────────
// contact_name is always resolved per-guest on the backend; never shown as a field.
const SYSTEM_FIELDS = {
  contact_name: null, // skip — auto-filled from guest record
  groom_name:   { label: 'שם החתן',            type: 'text', placeholder: 'דביר',    required: true  },
  bride_name:   { label: 'שם הכלה',            type: 'text', placeholder: 'ורד',    required: true  },
  venue:        { label: 'שם האולם / מקום',     type: 'text', placeholder: 'אולם הגן', required: true },
  event_date:   { label: 'תאריך האירוע',         type: 'date',                        required: true  },
  event_time:   { label: 'שעת ההתחלה (HH:mm)',  type: 'time',                        required: true  },
  guest_link:   null, // auto-generated per guest on the backend — never shown as a field
}

// Map system key → eventData field to pre-fill from
const EVENT_PREFILL = {
  groom_name: d => d?.partner1_name || '',
  bride_name: d => d?.partner2_name || '',
  venue:      d => d?.venue || d?.location || '',
  event_date: d => {
    if (!d?.date) return ''
    try { return new Date(d.date).toISOString().split('T')[0] } catch { return '' }
  },
  event_time: d => d?.event_time || '',
  // guest_link is auto-generated per-guest in the backend — not prefilled
}

// Render a template's body_text replacing {{N}} with param values
function renderTemplatePreview(bodyText, bodyParams, params) {
  if (!bodyText) return null
  return bodyText.replace(/\{\{(\d+)\}\}/g, (_m, n) => {
    const key = bodyParams?.[parseInt(n, 10) - 1]
    if (!key || key === 'contact_name') return '[שם האורח]'
    return params[key] || `[${key}]`
  })
}

const he = {
  title: 'שלח הזמנה בוואטסאפ',
  templateLabel: 'סוג הודעה',
  templateLoading: '...טוען תבניות',
  selectedGuests: 'אורחים שנבחרו',
  noPhone: 'אין טלפון',
  noPhones: 'לא נבחר אורח עם טלפון',
  allFields: 'יש למלא את כל השדות החובה',
  sending: 'שולח הזמנות...',
  send: 'שלח הזמנות',
  cancel: 'ביטול',
  close: 'סגור',
  results: 'תוצאות שליחה',
  succeeded: 'הצליחו',
  failed: 'נכשלו',
  success: 'הצליח',
  error: 'שגיאה',
  preview: 'תצוגה מקדימה של ההודעה',
  autoGuest: '(שם האורח ממולא אוטומטית)',
  paramsSection: 'פרמטרי ההודעה',
}

function WhatsAppInviteModal({ isOpen, onClose, selectedGuests = [], eventData = {}, onSend }) {
  const [params, setParams]                   = useState({})
  const [templates, setTemplates]             = useState([])
  const [selectedTemplateKey, setSelectedTemplateKey] = useState('wedding_invitation')
  const [templatesLoading, setTemplatesLoading] = useState(false)
  const [sending, setSending]                 = useState(false)
  const [results, setResults]                 = useState(null)
  const [showResults, setShowResults]         = useState(false)
  const [lastSendSnapshot, setLastSendSnapshot] = useState(null) // { params, templateKey }

  // Fetch templates when modal opens
  const fetchTemplates = () => {
    setTemplatesLoading(true)
    getWhatsAppTemplates()
      .then(data => {
        setTemplates(data.templates || [])
        if (data.templates?.length && !data.templates.find(t => t.key === selectedTemplateKey)) {
          setSelectedTemplateKey(data.templates[0].key)
        }
      })
      .catch(console.error)
      .finally(() => setTemplatesLoading(false))
  }

  useEffect(() => { if (isOpen) fetchTemplates() }, [isOpen])

  // Derive selected template object
  const selectedTemplate = useMemo(
    () => templates.find(t => t.key === selectedTemplateKey) || null,
    [templates, selectedTemplateKey]
  )

  // Unique param keys for this template (header + body, deduplicated, skip contact_name & guest_name_key & guest_link)
  const paramKeys = useMemo(() => {
    if (!selectedTemplate) return []
    const all = [
      ...(selectedTemplate.header_params || []),
      ...(selectedTemplate.body_params   || []),
    ]
    const seen = new Set()
    const gnk  = selectedTemplate.guest_name_key || ''
    return all.filter(k => {
      if (k === 'contact_name' || k === gnk || k === 'guest_link' || seen.has(k)) return false
      seen.add(k); return true
    })
  }, [selectedTemplate])

  // Re-init params whenever template or eventData changes
  useEffect(() => {
    const initial = {}
    for (const key of paramKeys) {
      const prefill = EVENT_PREFILL[key]
      initial[key] = prefill ? prefill(eventData) : ''
    }
    setParams(initial)
  }, [selectedTemplateKey, paramKeys.join(','), isOpen])

  const handleDeleteTemplate = async (key) => {
    if (!window.confirm(`האם למחוק את התבנית "${key}"? פעולה זו אינה הפיכה.`)) return
    try {
      await deleteWhatsAppTemplate(key)
      if (selectedTemplateKey === key) setSelectedTemplateKey('wedding_invitation')
      fetchTemplates()
    } catch (e) {
      alert(e?.response?.data?.detail || 'שגיאה במחיקת התבנית')
    }
  }

  const validateForm = () => {
    const hasPhones = selectedGuests.some(g => g.phone_number || g.phone)
    if (!hasPhones) { alert(he.noPhones); return false }

    for (const key of paramKeys) {
      const sysDef = SYSTEM_FIELDS[key]
      const isRequired = sysDef ? sysDef.required : true  // custom keys are required
      if (isRequired && !params[key]?.trim()) {
        const label = sysDef ? sysDef.label : key
        alert(`יש למלא: ${label}`)
        return false
      }
    }
    return true
  }

  const doSend = async (guestsToSend, paramsToUse, templateKey) => {
    setSending(true); setResults(null)
    try {
      if (onSend) {
        // Build extra_params: convert event_date to DD/MM if in YYYY-MM-DD format
        const extraParams = { ...paramsToUse }
        if (extraParams.event_date) {
          try {
            const [y, m, d] = extraParams.event_date.split('-')
            if (y && m && d) extraParams.event_date = `${d}/${m}`
          } catch {}
        }

        // Also provide legacy formData for backward compat
        const formData = {
          partner1:  paramsToUse.groom_name  || '',
          partner2:  paramsToUse.bride_name  || '',
          venue:     paramsToUse.venue       || '',
          eventDate: paramsToUse.event_date  || '',
          eventTime: paramsToUse.event_time  || '',
          // guestLink intentionally omitted — auto-generated per-guest in backend
        }

        const result = await onSend({
          formData,
          guestIds: guestsToSend.map(g => g.id),
          templateKey,
          extraParams,
        })
        setResults(result)
        setShowResults(true)
      }
    } catch (error) {
      setResults({
        total: guestsToSend.length,
        succeeded: 0,
        failed: guestsToSend.length,
        results: guestsToSend.map(guest => ({
          guest_id: guest.id,
          guest_name: guest.first_name,
          phone: guest.phone_number || guest.phone,
          status: 'failed',
          error: error.message
        }))
      })
      setShowResults(true)
    } finally {
      setSending(false)
    }
  }

  const handleSend = async () => {
    if (!validateForm()) return
    const snapshot = { params: { ...params }, templateKey: selectedTemplateKey }
    setLastSendSnapshot(snapshot)
    await doSend(selectedGuests, snapshot.params, snapshot.templateKey)
  }

  const handleResend = async () => {
    if (!results || !lastSendSnapshot) return
    const failedIds = new Set(
      results.results.filter(r => r.status === 'failed').map(r => r.guest_id)
    )
    const failedGuests = selectedGuests.filter(g => failedIds.has(String(g.id)))
    if (failedGuests.length === 0) return
    await doSend(failedGuests, lastSendSnapshot.params, lastSendSnapshot.templateKey)
  }

  const handleClose = () => { setResults(null); setShowResults(false); onClose() }

  if (!isOpen) return null

  // ── Results screen ────────────────────────────────────────────────────────
  if (showResults && results) {
    return (
      <div className="modal-overlay" onClick={handleClose}>
        <div className="modal-content whatsapp-modal" onClick={e => e.stopPropagation()}>
          <h2>{he.results}</h2>
          <div className="results-summary">
            <div className="result-stat success">
              <div className="stat-value">{results.succeeded}</div>
              <div className="stat-label">{he.succeeded}</div>
            </div>
            <div className="result-stat failed">
              <div className="stat-value">{results.failed}</div>
              <div className="stat-label">{he.failed}</div>
            </div>
          </div>
          <div className="results-list">
            {results.results.map((r, idx) => (
              <div key={idx} className={`result-item ${r.status}`}>
                <div className="result-header">
                  <span className="result-name">{r.guest_name}</span>
                  <span className={`result-status ${r.status}`}>{r.status === 'sent' ? he.success : he.error}</span>
                </div>
                <div className="result-phone">{r.phone}</div>
                {r.error && <div className="result-error">{r.error}</div>}
              </div>
            ))}
          </div>
          <div className="modal-buttons">
            {results.failed > 0 && (
              <button className="btn-warning" onClick={handleResend} disabled={sending}>
                {sending ? he.sending : `🔄 שלח שוב לנכשלים (${results.failed})`}
              </button>
            )}
            <button className="btn-primary" onClick={handleClose}>{he.close}</button>
          </div>
        </div>
      </div>
    )
  }

  // ── Form screen ───────────────────────────────────────────────────────────
  const previewText = renderTemplatePreview(
    selectedTemplate?.body_text,
    selectedTemplate?.body_params,
    params
  )

  return (
    <div className="modal-overlay" onClick={handleClose}>
      <div className="modal-content whatsapp-modal" onClick={e => e.stopPropagation()}>
        <h2>{he.title}</h2>

        {/* ── Template selector ── */}
        <div className="form-section template-selector">
          <div className="form-group">
            <div className="template-label-row">
              <label>{he.templateLabel}</label>
            </div>
            {templatesLoading ? (
              <span className="template-loading">{he.templateLoading}</span>
            ) : (
              <div className="template-select-row">
                <select
                  value={selectedTemplateKey}
                  onChange={e => setSelectedTemplateKey(e.target.value)}
                  disabled={sending}
                  className="template-select"
                >
                  {templates.length === 0 && (
                    <option value="wedding_invitation">הזמנה לחתונה</option>
                  )}
                  {templates.map(tpl => (
                    <option key={tpl.key} value={tpl.key}>
                      {tpl.friendly_name}{tpl.is_custom ? ' ✏️' : ''} ({tpl.body_param_count} פרמטרים)
                    </option>
                  ))}
                </select>
                {selectedTemplate?.is_custom && (
                  <button
                    className="btn-delete-template"
                    onClick={() => handleDeleteTemplate(selectedTemplateKey)}
                    disabled={sending}
                    title="מחק תבנית מותאמת"
                  >🗑️</button>
                )}
              </div>
            )}
            {selectedTemplate?.description && (
              <small className="template-description">{selectedTemplate.description}</small>
            )}
          </div>
        </div>

        {/* ── Guests list ── */}
        <div className="guests-preview">
          <div className="preview-header">{he.selectedGuests} ({selectedGuests.length})</div>
          <div className="guests-list">
            {selectedGuests.map((guest, idx) => (
              <div key={idx} className="guest-item">
                <span className="guest-name">{guest.first_name} {guest.last_name}</span>
                <span className={`guest-phone ${(guest.phone_number || guest.phone) ? '' : 'empty'}`}>
                  {guest.phone_number || guest.phone || he.noPhone}
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* ── Dynamic param form ── */}
        <div className="whatsapp-form">
          <div className="form-section">
            <h3>{he.paramsSection}</h3>

            {/* contact_name / guest_name_key auto-fill notes */}
            {(selectedTemplate?.header_params?.includes('contact_name') ||
              selectedTemplate?.body_params?.includes('contact_name')) && (
              <p className="auto-param-note">👤 {he.autoGuest}</p>
            )}
            {selectedTemplate?.guest_name_key && selectedTemplate.guest_name_key !== 'contact_name' && (
              <p className="auto-param-note">
                👤 הפרמטר <strong>{selectedTemplate.guest_name_key}</strong> ימולא אוטומטית משם האורח
              </p>
            )}
            {(selectedTemplate?.body_params?.includes('guest_link') ||
              selectedTemplate?.header_params?.includes('guest_link')) && (
              <p className="auto-param-note">🔗 קישור RSVP נוצר אוטומטית בנפרד לכל אורח</p>
            )}

            <div className="dynamic-params-grid">
              {paramKeys.map(key => {
                const sysDef = SYSTEM_FIELDS[key]
                if (sysDef === null) return null  // explicitly skip (contact_name)
                const label       = sysDef?.label       || key
                const inputType   = sysDef?.type        || 'text'
                const placeholder = sysDef?.placeholder || ''
                const required    = sysDef ? sysDef.required : true

                return (
                  <div key={key} className="form-group">
                    <label>{label}{required ? ' *' : ''}</label>
                    <input
                      type={inputType}
                      value={params[key] || ''}
                      onChange={e => setParams(p => ({ ...p, [key]: e.target.value }))}
                      placeholder={placeholder}
                      disabled={sending}
                      dir={inputType === 'text' || inputType === 'url' ? 'rtl' : undefined}
                    />
                  </div>
                )
              })}
            </div>
          </div>
        </div>

        {/* ── Message preview ── */}
        <div className="message-preview">
          <div className="preview-title">{he.preview}</div>
          <div className="preview-content">
            {previewText
              ? previewText
              : (selectedTemplate?.body_text || '— בחר תבנית —')}
          </div>
        </div>

        {/* ── Buttons ── */}
        <div className="modal-buttons">
          <button className="btn-primary" onClick={handleSend} disabled={sending}>
            {sending ? he.sending : he.send}
          </button>
          <button className="btn-secondary" onClick={handleClose} disabled={sending}>
            {he.cancel}
          </button>
        </div>
      </div>
    </div>
  )
}

export default WhatsAppInviteModal
