// frontend/src/modals/crm/customers/TransactionModal.jsx
// Record or edit a financial transaction for a customer

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'

const FLOW_OPTIONS = [
  { value: 'payment', label: 'Payment' },
  { value: 'invoice', label: 'Invoice' },
  { value: 'refund',  label: 'Refund'  },
  { value: 'credit',  label: 'Credit'  },
]

const PAYMENT_TYPE_OPTIONS = [
  { value: 'cash',          label: 'Cash'          },
  { value: 'bank_transfer', label: 'Bank Transfer' },
  { value: 'card',          label: 'Card'          },
  { value: 'paypal',        label: 'PayPal'        },
]

const CATEGORY_OPTIONS = [
  { value: 'full_payment', label: 'Full Payment' },
  { value: 'advance',      label: 'Advance'      },
  { value: 'installment',  label: 'Installment'  },
]


function emptyForm(user) {
  return {
    date: new Date().toISOString(),
    flow: 'payment',
    payment_type: 'cash',
    category: 'full_payment',
    amount: '',
    currency: 'EUR',
    invoice_ref: '',
    order_ref: '',
    recorded_by: user?.display_name || user?.name || '',
    note: '',
  }
}

export default function TransactionModal({ open, customerId, orders, initialData, editIndex, outstandingBalance, onClose, onSaved }) {
  const { toast } = useToast()
  const { user } = useAuth()
  const [form, setForm] = useState(() => emptyForm(user))
  const [saving, setSaving] = useState(false)

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }))

  useEffect(() => {
    if (!open) return
    if (initialData) {
      setForm({
        ...emptyForm(user),
        ...initialData,
        date: initialData.date || new Date().toISOString(),
      })
    } else {
      setForm(emptyForm(user))
    }
  }, [open, initialData])

  const isInvoice = form.flow === 'invoice'
  const isFullPayment = form.flow === 'payment' && form.category === 'full_payment'

  // Auto-fill amount for full payment
  useEffect(() => {
    if (initialData) return
    if (!isFullPayment) { set('amount', ''); return }
    if (form.order_ref) {
      const order = (orders || []).find(o => o.id === form.order_ref)
      const due = order?.payment_status?.balance_due ?? 0
      if (due > 0) set('amount', Number(due).toFixed(2))
    } else if (outstandingBalance != null && outstandingBalance > 0) {
      set('amount', outstandingBalance.toFixed(2))
    }
  }, [isFullPayment, form.order_ref])

  const handleSave = async () => {
    const parsedAmount = parseFloat(form.amount)
    if (!form.amount || !form.flow) {
      toast.warning('Required', 'Amount and flow type are required.')
      return
    }
    if (isNaN(parsedAmount) || parsedAmount < 0) {
      toast.warning('Invalid Amount', 'Amount must be 0 or greater.')
      return
    }
    if (!isInvoice && !form.category) {
      toast.warning('Required', 'Category is required.')
      return
    }

    setSaving(true)
    try {
      const payload = {
        ...form,
        amount: parsedAmount,
        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: isInvoice ? null : (form.payment_type || null),
        category: isInvoice ? 'full_payment' : (form.category || 'full_payment'),
      }
      let updated
      if (editIndex !== undefined && editIndex !== null) {
        updated = await api.patch(`/crm/customers/${customerId}/transactions/${editIndex}`, payload)
      } else {
        updated = await api.post(`/crm/customers/${customerId}/transactions`, payload)
      }
      toast.success('Saved', editIndex != null ? 'Transaction updated.' : 'Transaction recorded.')
      onSaved?.(updated)
      onClose()
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to save transaction.')
    } finally {
      setSaving(false)
    }
  }

  const isEditing = editIndex != null

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={isEditing ? 'Edit Transaction' : 'Record Transaction'}
      size="md"
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" loading={saving} onClick={handleSave}>
            {isEditing ? 'Update' : 'Save Transaction'}
          </Button>
        </>
      }
    >
      <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="date" value={form.date} onChange={iso => set('date', iso)} />
          <FormField label="Flow Type" name="flow" type="select" value={form.flow} onChange={e => set('flow', e.target.value)}>
            {FLOW_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
          </FormField>

          {!isInvoice && (
            <FormField label="Payment Type" name="payment_type" type="select" value={form.payment_type || ''} onChange={e => set('payment_type', e.target.value)}>
              <option value="">—</option>
              {PAYMENT_TYPE_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </FormField>
          )}

          {!isInvoice && (
            <FormField label="Category" name="category" type="select" value={form.category} onChange={e => set('category', e.target.value)}>
              {CATEGORY_OPTIONS.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
            </FormField>
          )}

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

          <FormField label="Invoice Ref" name="invoice_ref" type="text" value={form.invoice_ref || ''} onChange={e => set('invoice_ref', e.target.value)} placeholder="e.g. INV-2026-001" />
          <FormField label="Order Ref" name="order_ref" 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 style={{ gridColumn: '1 / -1' }}>
            <FormField label="Recorded By" name="recorded_by" type="text" value={form.recorded_by} onChange={e => set('recorded_by', e.target.value)} />
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <FormField label="Note" name="note" type="textarea" value={form.note} onChange={e => set('note', e.target.value)} placeholder="Optional note…" />
          </div>
        </div>
      </div>
    </Modal>
  )
}
