// frontend/src/modals/crm/customers/IssueModal.jsx
// Add or edit a technical issue or install-support entry

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 api from '@/lib/api'

// type: 'issue' → /technical-issues, 'support' → /install-support
const ENDPOINT = { issue: 'technical-issues', support: 'install-support' }

export default function IssueModal({ open, customerId, type, editIndex, initialData, onClose, user }) {
  const { toast } = useToast()
  const [form, setForm] = useState({ note: '', date: new Date().toISOString() })
  const [saving, setSaving] = useState(false)

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

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

  const endpoint = ENDPOINT[type] || 'technical-issues'
  const isEditing = editIndex != null

  const handleSave = async () => {
    if (!form.note.trim()) { toast.warning('Required', 'Please describe the issue.'); return }
    setSaving(true)
    try {
      let updated
      if (isEditing) {
        updated = await api.patch(`/crm/customers/${customerId}/${endpoint}/${editIndex}`, {
          note: form.note.trim(),
          opened_date: new Date(form.date).toISOString(),
        })
      } else {
        updated = await api.post(`/crm/customers/${customerId}/${endpoint}`, {
          note: form.note.trim(),
          opened_by: user?.display_name || user?.name || 'Staff',
          date: new Date(form.date).toISOString(),
        })
      }
      toast.success('Saved', isEditing ? 'Entry updated.' : 'Entry recorded.')
      onClose(updated)
    } catch (err) {
      toast.danger('Error', err.message || 'Failed to save entry.')
    } finally {
      setSaving(false)
    }
  }

  const titleMap = {
    issue:   isEditing ? 'Edit Technical Issue'  : 'Report Technical Issue',
    support: isEditing ? 'Edit Install Support'  : 'Report Install Support',
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title={titleMap[type] || 'Report Issue'}
      size="sm"
      footer={
        <>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" loading={saving} onClick={handleSave}>
            {isEditing ? 'Update' : 'Submit'}
          </Button>
        </>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <DateTimePicker label="Date & Time" name="date" value={form.date} onChange={iso => set('date', iso)} />
        <FormField label="Description" name="note" type="textarea" value={form.note} onChange={e => set('note', e.target.value)} placeholder="Describe the issue in detail…" />
      </div>
    </Modal>
  )
}
