// frontend/src/modals/devices/EditWarrantyModal.jsx
import { useState } from 'react'
import Modal from '@/components/ui/Modal'
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import api from '@/lib/api'

function parseFirestoreDate(str) {
  if (!str) return null
  if (typeof str === 'object') {
    const secs = str._seconds ?? str.seconds
    if (typeof secs === 'number') return new Date(secs * 1000)
    return null
  }
  const cleaned = str.replace(' at ', ' ').replace('UTC+0000', 'UTC').replace(/UTC\+(\d{4})/, 'UTC')
  const d = new Date(cleaned)
  return isNaN(d.getTime()) ? null : d
}

function formatDateNice(d) {
  if (!d) return '—'
  const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
  return `${d.getUTCDate()} ${months[d.getUTCMonth()]} ${d.getUTCFullYear()}`
}

export default function EditWarrantyModal({ open, onClose, onSaved, stats, id }) {
  const [active, setActive] = useState(String(stats?.warrantyActive ?? true))
  const [startDateStr, setStartDateStr] = useState(() => {
    const d = parseFirestoreDate(stats?.warrantyStart)
    return d ? d.toISOString().split('T')[0] : ''
  })
  const [period, setPeriod] = useState(stats?.warrantyPeriod || 0)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  const expiry = (() => {
    if (!startDateStr || !period) return null
    const d = new Date(startDateStr + 'T00:00:00Z')
    return new Date(d.getTime() + period * 86400000)
  })()

  const handleSave = async () => {
    setSaving(true)
    setError('')
    try {
      await api.put(`/devices/${id}`, {
        device_stats: {
          warrantyActive: active === 'true',
          warrantyStart: startDateStr ? startDateStr + 'T00:00:00Z' : stats?.warrantyStart,
          warrantyPeriod: period,
        },
      })
      await onSaved()
      onClose()
    } catch (err) {
      setError(err.message || 'Failed to save.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Edit Warranty"
      size="sm"
      footer={
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 'var(--space-3)' }}>
          <Button variant="ghost" onClick={onClose}>Cancel</Button>
          <Button variant="primary" loading={saving} onClick={handleSave}>Save</Button>
        </div>
      }
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
        <FormField
          label="Warranty Status"
          name="active"
          type="select"
          value={active}
          onChange={(e) => setActive(e.target.value)}
        >
          <option value="true">Active</option>
          <option value="false">Voided</option>
        </FormField>
        {active === 'false' && (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>
            Warning: Setting this to Voided will mark the warranty as void, even if it has not yet expired.
          </p>
        )}
        <FormField
          label="Start Date"
          name="startDate"
          type="date"
          value={startDateStr}
          onChange={(e) => setStartDateStr(e.target.value)}
        />
        <FormField
          label="Period (days)"
          name="period"
          type="number"
          value={String(period)}
          onChange={(e) => setPeriod(Math.max(0, parseInt(e.target.value) || 0))}
          hint={expiry ? `Expiry: ${formatDateNice(expiry)}` : undefined}
          inputProps={{ min: 0 }}
        />
        <div style={{ display: 'flex', gap: 'var(--space-2)', flexWrap: 'wrap' }}>
          {[{ label: '+1 Month', days: 30 }, { label: '+6 Months', days: 180 }, { label: '+1 Year', days: 365 }].map((q) => (
            <Button
              key={q.label}
              variant="secondary"
              size="sm"
              onClick={() => setPeriod((p) => Math.max(0, p + q.days))}
            >
              {q.label}
            </Button>
          ))}
        </div>
        {error && (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
        )}
      </div>
    </Modal>
  )
}
