// frontend/src/modals/devices/EditLocationModal.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'

export default function EditLocationModal({ open, onClose, onSaved, device, id }) {
  const [locName, setLocName] = useState(device?.device_location || '')
  const [lat, setLat] = useState(() => {
    const c = device?.device_location_coordinates
    if (!c) return ''
    const v = c?.lat ?? c?.latitude
    return v != null ? String(v) : ''
  })
  const [lng, setLng] = useState(() => {
    const c = device?.device_location_coordinates
    if (!c) return ''
    const v = c?.lng ?? c?.longitude
    return v != null ? String(v) : ''
  })
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  const handleSave = async () => {
    setSaving(true)
    setError('')
    const latNum = parseFloat(lat)
    const lngNum = parseFloat(lng)
    const coordPayload = (!isNaN(latNum) && !isNaN(lngNum))
      ? { lat: latNum, lng: lngNum }
      : device?.device_location_coordinates ?? null
    try {
      await api.put(`/devices/${id}`, {
        device_location: locName,
        device_location_coordinates: coordPayload,
      })
      await onSaved()
      onClose()
    } catch (err) {
      setError(err.message || 'Failed to save.')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      onClose={onClose}
      title="Edit Device Location"
      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="Location Name"
          name="locName"
          value={locName}
          onChange={(e) => setLocName(e.target.value)}
          placeholder="e.g. Saint Mary's Church"
          hint={`${locName.length}/35 characters`}
          inputProps={{ maxLength: 35 }}
        />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-3)' }}>
          <FormField
            label="Latitude"
            name="lat"
            type="number"
            value={lat}
            onChange={(e) => setLat(e.target.value)}
            placeholder="e.g. 37.9838"
            inputProps={{ step: '0.0000001' }}
          />
          <FormField
            label="Longitude"
            name="lng"
            type="number"
            value={lng}
            onChange={(e) => setLng(e.target.value)}
            placeholder="e.g. 23.7275"
            inputProps={{ step: '0.0000001' }}
          />
        </div>
        {!isNaN(parseFloat(lat)) && !isNaN(parseFloat(lng)) && (
          <a
            href={`https://www.google.com/maps?q=${lat},${lng}`}
            target="_blank"
            rel="noopener noreferrer"
            style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-accent)' }}
          >
            Preview on Google Maps ↗
          </a>
        )}
        {error && (
          <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-danger)' }}>{error}</p>
        )}
      </div>
    </Modal>
  )
}
