// frontend/src/modals/crm/QuickEntryModals.jsx
// Quick-entry modals for the Customer Detail page:
//   InitNegotiationsModal  — create a new order at negotiating stage
//   SendMessageModal       — compose and send an email
//   RecordIssueModal       — log a tech issue or install-support ticket
//   RecordPaymentModal     — record a payment / invoice transaction
//   AddFilesModal          — placeholder for file upload flow (to be wired to Nextcloud)

import { useState, useEffect } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import DateTimePicker from '@/components/ui/DateTimePicker'
import { useToast } from '@/components/ui/Toast'
import { useAuth } from '@/hooks/useAuth'
import api from '@/lib/api'

// ─── Init Negotiations Modal ──────────────────────────────────────────────────

export function InitNegotiationsModal({ open, customerId, onClose, onSuccess }) {
  const { toast } = useToast()
  const { user } = useAuth()
  const [form, setForm] = useState({ date: new Date().toISOString(), title: '', note: '' })
  const [saving, setSaving] = useState(false)
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }))

  useEffect(() => { if (open) setForm({ date: new Date().toISOString(), title: '', note: '' }) }, [open])

  const handleConfirm = async () => {
    if (!form.title.trim()) { toast.warning('Required', 'Title is required.'); return }
    setSaving(true)
    try {
      await api.post(`/crm/customers/${customerId}/orders/init-negotiations`, {
        title: form.title.trim(),
        note:  form.note.trim(),
        date:  form.date ? new Date(form.date).toISOString() : new Date().toISOString(),
        created_by: user?.display_name || user?.name || 'Staff',
      })
      // Promote customer to Active when a new order is initiated
      try { await api.patch(`/crm/customers/${customerId}/relationship-status`, { status: 'active' }) } catch { /* non-critical */ }
      toast.success('Order created', 'Negotiations started successfully.')
      onSuccess?.()
      onClose()
    } catch (err) {
      toast.danger('Failed', err.message || 'Could not create order.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Init Negotiations"
      size="sm"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
          <Button variant="ghost" onClick={onClose} disabled={saving}>Cancel</Button>
          <Button variant="primary" onClick={handleConfirm} loading={saving}>Create Order</Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <DateTimePicker
          label="Date & Time"
          name="neg-date"
          value={form.date}
          onChange={iso => set('date', iso)}
        />
        <FormField
          label="Title"
          name="neg-title"
          type="text"
          value={form.title}
          onChange={e => set('title', e.target.value)}
          placeholder="e.g. 3× Wall Mount Units — Athens Office"
          required
          inputProps={{ autoFocus: true }}
        />
        <FormField
          label="Quick Note"
          name="neg-note"
          type="textarea"
          value={form.note}
          onChange={e => set('note', e.target.value)}
          placeholder="Initial context or customer request..."
          rows={3}
        />
      </div>
    </Modal>
  )
}

// ─── Send Message Modal ───────────────────────────────────────────────────────

export function SendMessageModal({ open, customer, onClose, onSent }) {
  const { toast } = useToast()

  // Pre-fill "to" from the customer's primary email contact
  const primaryEmail = customer?.contact_details?.find(c => c.type === 'email')?.value || ''

  const [form, setForm] = useState({ to: '', subject: '', body: '' })
  const [sending, setSending] = useState(false)
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }))

  useEffect(() => {
    if (open) setForm({ to: primaryEmail, subject: '', body: '' })
  }, [open, primaryEmail])

  const canSend = form.to.trim() && form.subject.trim() && form.body.trim()

  const handleSend = async () => {
    if (!canSend) return
    setSending(true)
    try {
      await api.post('/crm/comms/email/send', {
        to:      form.to.trim(),
        subject: form.subject.trim(),
        body:    form.body.trim(),
      })
      toast.success('Email sent', `Message delivered to ${form.to.trim()}.`)
      onSent?.()
      onClose()
    } catch (err) {
      toast.danger('Failed to send', err.message || 'Could not send email.')
    } finally {
      setSending(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Send Message"
      size="md"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
          <Button variant="ghost" onClick={onClose} disabled={sending}>Cancel</Button>
          <Button variant="primary" onClick={handleSend} loading={sending} disabled={!canSend}>Send</Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <FormField
          label="To"
          name="msg-to"
          type="email"
          value={form.to}
          onChange={e => set('to', e.target.value)}
          placeholder="recipient@example.com"
          required
          inputProps={{ autoFocus: true }}
        />
        <FormField
          label="Subject"
          name="msg-subject"
          type="text"
          value={form.subject}
          onChange={e => set('subject', e.target.value)}
          placeholder="Email subject..."
          required
        />
        <FormField
          label="Message"
          name="msg-body"
          type="textarea"
          value={form.body}
          onChange={e => set('body', e.target.value)}
          placeholder="Write your message here..."
          rows={6}
          required
        />
      </div>
    </Modal>
  )
}

// ─── Record Issue Modal ───────────────────────────────────────────────────────

export function RecordIssueModal({ open, customerId, onClose, onSuccess }) {
  const { toast } = useToast()
  const { user } = useAuth()
  const [type, setType]   = useState('issue') // 'issue' | 'support'
  const [form, setForm]   = useState({ date: new Date().toISOString(), note: '' })
  const [saving, setSaving] = useState(false)
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }))

  useEffect(() => { if (open) { setType('issue'); setForm({ date: new Date().toISOString(), note: '' }) } }, [open])

  const handleConfirm = async () => {
    if (!form.note.trim()) { toast.warning('Required', 'A note is required.'); return }
    setSaving(true)
    const endpoint = type === 'issue' ? 'technical-issues' : 'install-support'
    try {
      await api.post(`/crm/customers/${customerId}/${endpoint}`, {
        note:       form.note.trim(),
        opened_by:  user?.display_name || user?.name || 'Staff',
        date:       form.date ? new Date(form.date).toISOString() : new Date().toISOString(),
      })
      toast.success('Recorded', type === 'issue' ? 'Tech issue logged.' : 'Support request logged.')
      onSuccess?.()
      onClose()
    } catch (err) {
      toast.danger('Failed', err.message || 'Could not record issue.')
    } finally {
      setSaving(false)
    }
  }

  const isIssue   = type === 'issue'
  const isSupport = type === 'support'

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Record Issue / Support"
      size="sm"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
          <Button variant="ghost" onClick={onClose} disabled={saving}>Cancel</Button>
          <Button variant="primary" onClick={handleConfirm} loading={saving}>Submit</Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        {/* Type segmented toggle */}
        <div style={{
          display: 'flex',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-strong)',
          overflow: 'hidden',
        }}>
          {[['issue', 'Technical Issue'], ['support', 'Install Support']].map(([v, label]) => (
            <button
              key={v}
              type="button"
              onClick={() => setType(v)}
              style={{
                flex: 1,
                padding: 'var(--space-2) 0',
                fontSize: 'var(--font-size-sm)',
                fontWeight: 'var(--font-weight-semibold)',
                cursor: 'pointer',
                border: 'none',
                transition: 'background-color var(--transition-fast), color var(--transition-fast)',
                backgroundColor: type === v
                  ? v === 'issue' ? 'var(--color-danger-bg)' : 'var(--color-warning-bg)'
                  : 'transparent',
                color: type === v
                  ? v === 'issue' ? 'var(--color-danger)' : 'var(--color-warning)'
                  : 'var(--color-text-muted)',
              }}
            >
              {label}
            </button>
          ))}
        </div>

        <DateTimePicker
          label="Date & Time"
          name="issue-date"
          value={form.date}
          onChange={iso => set('date', iso)}
        />
        <FormField
          label="Note"
          name="issue-note"
          type="textarea"
          value={form.note}
          onChange={e => set('note', e.target.value)}
          placeholder={isIssue ? 'Describe the technical issue...' : 'Describe the support request...'}
          rows={4}
          required
          inputProps={{ autoFocus: true }}
        />
      </div>
    </Modal>
  )
}

// ─── Record Payment Modal ─────────────────────────────────────────────────────

const FLOW_LABELS = {
  payment: 'Payment',
  invoice: 'Invoice',
  refund:  'Refund',
  credit:  'Credit Note',
}

const PAYMENT_TYPE_LABELS = {
  cash:         'Cash',
  bank_transfer: 'Bank Transfer',
  card:         'Card',
  cheque:       'Cheque',
  crypto:       'Crypto',
  other:        'Other',
}

const TRANSACTION_CATEGORY_LABELS = {
  deposit:      'Deposit',
  full_payment: 'Full Payment',
  partial:      'Partial Payment',
  advance:      'Advance',
  other:        'Other',
}

export function RecordPaymentModal({ open, customerId, orders = [], onClose, onSuccess }) {
  const { toast } = useToast()
  const { user } = useAuth()

  const emptyForm = () => ({
    date:         new Date().toISOString(),
    flow:         'payment',
    payment_type: 'bank_transfer',
    category:     'full_payment',
    amount:       '',
    currency:     'EUR',
    invoice_ref:  '',
    order_ref:    '',
    note:         '',
  })

  const [form, setForm]   = useState(emptyForm)
  const [saving, setSaving] = useState(false)
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }))

  useEffect(() => { if (open) setForm(emptyForm()) }, [open])

  const handleConfirm = async () => {
    if (!form.amount) { toast.warning('Required', 'Amount is required.'); return }
    setSaving(true)
    try {
      await api.post(`/crm/customers/${customerId}/transactions`, {
        ...form,
        amount:       parseFloat(form.amount) || 0,
        date:         form.date ? new Date(form.date).toISOString() : new Date().toISOString(),
        invoice_ref:  form.invoice_ref || null,
        order_ref:    form.order_ref   || null,
        payment_type: form.flow === 'invoice' ? null : (form.payment_type || null),
        recorded_by:  user?.display_name || user?.name || 'Staff',
        note:         form.note || '',
      })
      toast.success('Recorded', 'Transaction saved successfully.')
      onSuccess?.()
      onClose()
    } catch (err) {
      toast.danger('Failed', err.message || 'Could not record payment.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Record Payment"
      size="md"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
          <Button variant="ghost" onClick={onClose} disabled={saving}>Cancel</Button>
          <Button variant="primary" onClick={handleConfirm} loading={saving}>Record</Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)' }}>
          <DateTimePicker
            label="Date & Time"
            name="pay-date"
            value={form.date}
            onChange={iso => set('date', iso)}
          />
          <FormField
            label="Flow"
            name="pay-flow"
            type="select"
            value={form.flow}
            onChange={e => set('flow', e.target.value)}
          >
            {Object.entries(FLOW_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
          </FormField>

          {form.flow !== 'invoice' && (
            <FormField
              label="Payment Type"
              name="pay-type"
              type="select"
              value={form.payment_type}
              onChange={e => set('payment_type', e.target.value)}
            >
              {Object.entries(PAYMENT_TYPE_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
            </FormField>
          )}

          <FormField
            label="Category"
            name="pay-category"
            type="select"
            value={form.category}
            onChange={e => set('category', e.target.value)}
          >
            {Object.entries(TRANSACTION_CATEGORY_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
          </FormField>

          <FormField
            label="Amount"
            name="pay-amount"
            type="number"
            value={form.amount}
            onChange={e => set('amount', e.target.value)}
            placeholder="0.00"
            required
            inputProps={{ min: '0', step: '0.01', autoFocus: true }}
          />
          <FormField
            label="Currency"
            name="pay-currency"
            type="select"
            value={form.currency}
            onChange={e => set('currency', e.target.value)}
          >
            {['EUR', 'USD', 'GBP', 'CHF'].map(c => <option key={c} value={c}>{c}</option>)}
          </FormField>

          <FormField
            label="Invoice Ref"
            name="pay-invoice"
            type="text"
            value={form.invoice_ref}
            onChange={e => set('invoice_ref', e.target.value)}
            placeholder="INV-2026-001"
          />
          <FormField
            label="Order Ref"
            name="pay-order"
            type="select"
            value={form.order_ref}
            onChange={e => set('order_ref', e.target.value)}
          >
            <option value="">— None —</option>
            {orders.map(o => (
              <option key={o.id} value={o.id}>
                {o.order_number || o.id.slice(0, 8)}{o.title ? ` — ${o.title}` : ''}
              </option>
            ))}
          </FormField>
        </div>

        <FormField
          label="Note"
          name="pay-note"
          type="textarea"
          value={form.note}
          onChange={e => set('note', e.target.value)}
          placeholder="Optional note..."
          rows={2}
        />
      </div>
    </Modal>
  )
}

// ─── Add Files Modal ──────────────────────────────────────────────────────────

export function AddFilesModal({ open, customerId, onClose, onSuccess }) {
  const { toast } = useToast()
  // Placeholder — full implementation will hook into Nextcloud upload flow
  // The actual file upload UI is built in the Files & Media tab

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Add Files"
      size="sm"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
          <Button variant="ghost" onClick={onClose}>Close</Button>
        </div>
      }
    >
      <div style={{
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: 'var(--space-4)',
        padding: 'var(--space-8) var(--space-4)',
        textAlign: 'center',
      }}>
        <div style={{
          width: 56,
          height: 56,
          borderRadius: 'var(--radius-xl)',
          backgroundColor: 'var(--color-primary-subtle)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round" strokeLinejoin="round" style={{ color: 'var(--color-primary)' }}>
            <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>
            <polyline points="17 8 12 3 7 8"/>
            <line x1="12" y1="3" x2="12" y2="15"/>
          </svg>
        </div>
        <div>
          <p style={{ fontSize: 'var(--font-size-base)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', marginBottom: 'var(--space-1)' }}>
            File Upload
          </p>
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
            Open the <strong style={{ color: 'var(--color-text-secondary)' }}>Files &amp; Media</strong> tab to manage and upload files for this customer.
          </p>
        </div>
        <Button variant="secondary" onClick={() => { onClose(); onSuccess?.() }}>
          Go to Files &amp; Media
        </Button>
      </div>
    </Modal>
  )
}
