// frontend/src/modals/crm/LegacyQuotationModal.jsx
// Add / Edit a legacy (pre-system) quotation with optional PDF upload

import { useState } from 'react'
import api from '@/lib/api'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import { toDateInput } from '@/lib/formatters'

const STATUSES = ['draft', 'sent', 'accepted', 'rejected']

export default function LegacyQuotationModal({ customerId, existing, onClose, onSaved }) {
  const isEdit = !!existing

  const [form, setForm] = useState({
    title: existing?.title || '',
    legacy_date: existing?.legacy_date || toDateInput(new Date()),
    status: existing?.status || 'sent',
    final_total: existing?.final_total != null ? String(existing.final_total) : '',
  })
  const [pdfFile, setPdfFile] = useState(null)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

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

  async function handleSave() {
    if (!form.title.trim()) { setError('Title is required'); return }
    setSaving(true)
    setError('')
    try {
      let quotation
      if (isEdit) {
        quotation = await api.put(`/crm/quotations/${existing.id}`, {
          title: form.title,
          status: form.status,
          legacy_date: form.legacy_date || null,
          extras_cost: parseFloat(form.final_total) || 0,
        })
      } else {
        quotation = await api.post('/crm/quotations', {
          customer_id: customerId,
          title: form.title,
          status: form.status,
          is_legacy: true,
          legacy_date: form.legacy_date || null,
          extras_cost: parseFloat(form.final_total) || 0,
        })
      }

      if (pdfFile) {
        await api.upload(`/crm/quotations/${quotation.id}/legacy-pdf`, pdfFile)
      }

      onSaved()
      onClose()
    } catch (e) {
      setError(e?.message || 'Failed to save')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open
      onClose={onClose}
      title={isEdit ? 'Edit Legacy Quotation' : 'Add Legacy Quotation'}
      size="sm"
      footer={
        <div style={{ display: 'flex', gap: 'var(--space-2)', justifyContent: 'flex-end' }}>
          <Button variant="secondary" size="md" onClick={onClose} disabled={saving}>
            Cancel
          </Button>
          <Button variant="primary" size="md" loading={saving} onClick={handleSave}>
            {isEdit ? 'Save Changes' : 'Add Legacy'}
          </Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <FormField
          label="Title"
          name="legacy-title"
          value={form.title}
          onChange={e => set('title', e.target.value)}
          placeholder="e.g. Church Sound System Offer"
          required
        />

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
          <FormField
            label="Date"
            name="legacy-date"
            type="text"
            value={form.legacy_date}
            onChange={e => set('legacy_date', e.target.value)}
            inputProps={{ type: 'date' }}
          />
          <FormField
            label="Status"
            name="legacy-status"
            type="select"
            value={form.status}
            onChange={e => set('status', e.target.value)}
          >
            {STATUSES.map(s => (
              <option key={s} value={s}>{s.charAt(0).toUpperCase() + s.slice(1)}</option>
            ))}
          </FormField>
        </div>

        <FormField
          label="Total Amount (€)"
          name="legacy-total"
          type="number"
          value={form.final_total}
          onChange={e => set('final_total', e.target.value)}
          placeholder="0.00"
          inputProps={{ min: 0, step: '0.01' }}
        />

        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
          <label style={{
            fontSize: 'var(--font-size-sm)',
            fontWeight: 'var(--font-weight-medium)',
            color: 'var(--color-text-secondary)',
          }}>
            PDF File <span style={{ color: 'var(--color-text-muted)', fontWeight: 400 }}>(optional)</span>
          </label>
          <input
            type="file"
            accept="application/pdf"
            onChange={e => setPdfFile(e.target.files?.[0] || null)}
            className="input"
            style={{ paddingTop: 'var(--space-2)', paddingBottom: 'var(--space-2)' }}
          />
          {existing?.legacy_pdf_path && !pdfFile && (
            <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
              Current: {existing.legacy_pdf_path.split('/').pop()}
            </span>
          )}
        </div>

        {error && (
          <div style={{
            fontSize: 'var(--font-size-sm)',
            color: 'var(--color-danger)',
            padding: 'var(--space-2) var(--space-3)',
            backgroundColor: 'var(--color-danger-bg)',
            borderRadius: 'var(--radius-md)',
          }}>
            {error}
          </div>
        )}
      </div>
    </Modal>
  )
}
