import { type FormEvent, useEffect, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { fetchStaffMember, updateStaff } from '../../api/staff'

export function StaffEditPage() {
  const { staffId } = useParams()
  const navigate = useNavigate()
  const id = Number(staffId)
  const [firstname, setFirstname] = useState('')
  const [lastname, setLastname] = useState('')
  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!id) return
    let cancelled = false
    ;(async () => {
      try {
        const data = await fetchStaffMember(id)
        if (cancelled) return
        const u = (data.user ?? data.staff ?? {}) as Record<string, unknown>
        setFirstname(String(u.firstname ?? ''))
        setLastname(String(u.lastname ?? ''))
        setEmail(String(u.email ?? ''))
        setPhone(String(u.phone ?? ''))
        setError(null)
      } catch (e) {
        if (!cancelled) setError(e instanceof Error ? e.message : 'Unable to load staff.')
      }
    })()
    return () => {
      cancelled = true
    }
  }, [id])

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    if (!id) return
    try {
      await updateStaff(id, { firstname, lastname, email, phone })
      navigate('/app/staff')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to update staff.')
    }
  }

  return (
    <div className="container mt-4">
      <h2>Edit Staff Member</h2>
      {error ? <div className="alert alert-danger">{error}</div> : null}
      <form onSubmit={(e) => void onSubmit(e)}>
        <div className="mb-3">
          <label className="form-label">First Name</label>
          <input
            type="text"
            className="form-control"
            value={firstname}
            onChange={(e) => setFirstname(e.target.value)}
            required
          />
        </div>
        <div className="mb-3">
          <label className="form-label">Last Name</label>
          <input
            type="text"
            className="form-control"
            value={lastname}
            onChange={(e) => setLastname(e.target.value)}
            required
          />
        </div>
        <div className="mb-3">
          <label className="form-label">Email</label>
          <input
            type="email"
            className="form-control"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </div>
        <div className="mb-3">
          <label className="form-label">Phone Number</label>
          <input
            type="tel"
            name="phone"
            className="form-control"
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            placeholder="Enter phone number"
          />
        </div>
        <button type="submit" className="btn btn-primary">
          Update
        </button>
      </form>
    </div>
  )
}
