// frontend/src/modals/devices/EditSubscriptionModal.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()}`
}

const TIERS = ['basic', 'small', 'mini', 'premium', 'vip', 'custom']

export default function EditSubscriptionModal({ open, onClose, onSaved, sub, id }) {
  const [tier, setTier] = useState(sub?.subscrTier || 'basic')
  const [startDateStr, setStartDateStr] = useState(() => {
    const d = parseFirestoreDate(sub?.subscrStart)
    return d ? d.toISOString().split('T')[0] : ''
  })
  const [duration, setDuration] = useState(sub?.subscrDuration || 0)
  const [maxUsers, setMaxUsers] = useState(String(sub?.maxUsers || 1))
  const [maxOutputs, setMaxOutputs] = useState(String(sub?.maxOutputs || 1))
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

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

  const handleSave = async () => {
    setSaving(true)
    setError('')
    try {
      await api.put(`/devices/${id}`, {
        device_subscription: {
          subscrTier: tier,
          subscrStart: startDateStr ? startDateStr + 'T00:00:00Z' : sub?.subscrStart,
          subscrDuration: duration,
          maxUsers: Number(maxUsers),
          maxOutputs: Number(maxOutputs),
        },
      })
      await onSaved()
      onClose()
    } catch (err) {
      setError(err.message || 'Failed to save.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Edit Subscription"
      size="md"
      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="Tier"
          name="tier"
          type="select"
          value={tier}
          onChange={(e) => setTier(e.target.value)}
        >
          {TIERS.map((t) => (
            <option key={t} value={t}>{t.charAt(0).toUpperCase() + t.slice(1)}</option>
          ))}
        </FormField>
        <FormField
          label="Start Date"
          name="startDate"
          type="date"
          value={startDateStr}
          onChange={(e) => setStartDateStr(e.target.value)}
        />
        <FormField
          label="Duration (days)"
          name="duration"
          type="number"
          value={String(duration)}
          onChange={(e) => setDuration(Math.max(0, parseInt(e.target.value) || 0))}
          hint={endDate ? `End date: ${formatDateNice(endDate)}` : 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={() => setDuration((d) => Math.max(0, d + q.days))}
            >
              {q.label}
            </Button>
          ))}
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
          <FormField
            label="Max Users"
            name="maxUsers"
            type="select"
            value={maxUsers}
            onChange={(e) => setMaxUsers(e.target.value)}
          >
            {Array.from({ length: 10 }, (_, i) => i + 1).map((n) => (
              <option key={n} value={String(n)}>{n} {n === 1 ? 'User' : 'Users'}</option>
            ))}
          </FormField>
          <FormField
            label="Max Outputs"
            name="maxOutputs"
            type="select"
            value={maxOutputs}
            onChange={(e) => setMaxOutputs(e.target.value)}
          >
            {Array.from({ length: 16 }, (_, i) => i + 1).map((n) => (
              <option key={n} value={String(n)}>{n} {n === 1 ? 'Output' : 'Outputs'}</option>
            ))}
          </FormField>
        </div>
        {error && (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
        )}
      </div>
    </Modal>
  )
}
