/**
 * EditLocationModal — edit non-PK fields of a location record (M2-T10, reused by T09).
 *
 * Editable fields: latitude, longitude, altitude.
 * Read-only: person + datetime (composite PK).
 */

import { useState } from 'react'
import {
  Modal,
  Stack,
  NumberInput,
  Button,
  Group,
  Text,
  Alert,
} from '@mantine/core'
import { useUpdateLocation } from './hooks'
import type { LocationRecord, LocationUpdateBody } from './hooks'

export interface EditLocationModalProps {
  record: LocationRecord
  onClose: () => void
  onSaved: () => void
}

export function EditLocationModal({ record, onClose, onSaved }: EditLocationModalProps) {
  const [latitude, setLatitude] = useState<number | string>(record.latitude)
  const [longitude, setLongitude] = useState<number | string>(record.longitude)
  const [altitude, setAltitude] = useState<number | string>(record.altitude ?? '')
  const [error, setError] = useState<string | null>(null)

  const updateMutation = useUpdateLocation()

  function validate(): string | null {
    const lat = Number(latitude)
    const lng = Number(longitude)
    if (isNaN(lat) || lat < -90 || lat > 90) return 'Latitude must be a number between -90 and 90.'
    if (isNaN(lng) || lng < -180 || lng > 180)
      return 'Longitude must be a number between -180 and 180.'
    // Altitude is optional — blank is fine.
    if (altitude !== '' && altitude !== null && isNaN(Number(altitude)))
      return 'Altitude must be a number or left blank.'
    return null
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    setError(null)

    const validationError = validate()
    if (validationError) {
      setError(validationError)
      return
    }

    const body: LocationUpdateBody = {
      latitude: Number(latitude),
      longitude: Number(longitude),
      altitude: altitude === '' || altitude === null ? null : Number(altitude),
    }

    try {
      await updateMutation.mutateAsync({
        person: record.person,
        datetime: record.datetime,
        body,
      })
      onSaved()
      onClose()
    } catch {
      setError('Failed to save. Please try again.')
    }
  }

  return (
    <Modal
      opened
      onClose={onClose}
      title="Edit Location Record"
      size="sm"
      data-testid="edit-location-modal"
    >
      <form onSubmit={handleSubmit} data-testid="edit-location-form">
        <Stack gap="sm">
          {/* Composite PK — read-only */}
          <Text size="sm" c="dimmed">
            <strong>Person (PK):</strong> {record.person}
          </Text>
          <Text size="sm" c="dimmed">
            <strong>Datetime (PK):</strong> {record.datetime}
          </Text>

          <NumberInput
            label="Latitude"
            value={latitude}
            onChange={(val) => setLatitude(val)}
            decimalScale={6}
            data-testid="location-latitude-input"
          />

          <NumberInput
            label="Longitude"
            value={longitude}
            onChange={(val) => setLongitude(val)}
            decimalScale={6}
            data-testid="location-longitude-input"
          />

          <NumberInput
            label="Altitude (optional)"
            value={altitude}
            onChange={(val) => setAltitude(val)}
            decimalScale={2}
            placeholder="Leave blank to clear"
            data-testid="location-altitude-input"
          />

          {error && (
            <Alert color="red" data-testid="edit-location-error">
              {error}
            </Alert>
          )}

          <Group justify="flex-end" gap="sm">
            <Button variant="default" onClick={onClose} data-testid="edit-location-cancel">
              Cancel
            </Button>
            <Button
              type="submit"
              loading={updateMutation.isPending}
              data-testid="edit-location-submit"
            >
              Save
            </Button>
          </Group>
        </Stack>
      </form>
    </Modal>
  )
}
