import { type FormEvent, useState } from 'react'
import { Link } from 'react-router-dom'
import { FormModal } from './FormModal'
import type { Route, CreateRouteInput, UpdateRouteInput } from '../../types'

interface RouteFormModalProps {
  route?: Route
  nextOrder?: number
  onSubmit: (data: CreateRouteInput | UpdateRouteInput) => void
  onClose: () => void
  isSubmitting?: boolean
  onDelete?: () => void
  isDeleting?: boolean
  detailUrl?: string
}

export function RouteFormModal({ route, nextOrder, onSubmit, onClose, isSubmitting, onDelete, isDeleting, detailUrl }: RouteFormModalProps) {
  const [name, setName] = useState(route?.name ?? '')
  const [order, setOrder] = useState(String(route?.order ?? nextOrder ?? 0))
  const [pinwheelZone, setPinwheelZone] = useState(
    route?.pinwheelZone != null ? String(route.pinwheelZone) : ''
  )

  const handleSubmit = (e: FormEvent) => {
    e.preventDefault()
    onSubmit({
      name,
      order: Number(order),
      pinwheelZone: pinwheelZone !== '' ? Number(pinwheelZone) : null,
    })
  }

  return (
    <FormModal
      title={route ? 'Edit Route' : 'Add Route'}
      onClose={onClose}
      onSubmit={handleSubmit}
      isSubmitting={isSubmitting}
      onDelete={onDelete}
      isDeleting={isDeleting}
      headerExtra={detailUrl ? (
        <Link
          to={detailUrl}
          className="text-sm text-blue-600 dark:text-blue-400 hover:underline"
        >
          View Encounters
        </Link>
      ) : undefined}
    >
      <div>
        <label className="block text-sm font-medium mb-1">Name</label>
        <input
          type="text"
          required
          value={name}
          onChange={(e) => setName(e.target.value)}
          className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Order</label>
        <input
          type="number"
          required
          min={0}
          value={order}
          onChange={(e) => setOrder(e.target.value)}
          className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
        />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Pinwheel Zone</label>
        <input
          type="number"
          min={0}
          value={pinwheelZone}
          onChange={(e) => setPinwheelZone(e.target.value)}
          placeholder="None"
          className="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600"
        />
        <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
          Routes in the same zone share an encounter when the Pinwheel Clause is active
        </p>
      </div>
    </FormModal>
  )
}
