import { type FormEvent, useEffect, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchPermission, updatePermission } from '../../api/rolePermission'
import { ROLE_PERMISSION_BASE } from './rolePermissionPaths'

export function EditPermissionPage() {
  const { permissionId } = useParams<{ permissionId: string }>()
  const navigate = useNavigate()
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [loading, setLoading] = useState(true)
  const [msg, setMsg] = useState<string | null>(null)

  useEffect(() => {
    if (!permissionId) return
    fetchPermission(permissionId)
      .then((d) => {
        const p = d.permission
        if (p) {
          setName(String(p.name ?? ''))
          setDescription(String(p.description ?? ''))
        }
      })
      .catch(() => setMsg('Could not load permission.'))
      .finally(() => setLoading(false))
  }, [permissionId])

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    if (!permissionId) return
    setMsg(null)
    try {
      await updatePermission(permissionId, { name, description })
      navigate(`${ROLE_PERMISSION_BASE}/list_permissions`)
    } catch (err: unknown) {
      setMsg(err instanceof ApiHttpError ? err.message : 'Update failed.')
    }
  }

  if (!permissionId) return <div className="container mt-4">Missing id.</div>
  if (loading) return <div className="container mt-4">Loading…</div>

  return (
    <div className="container mt-4">
      <h3>Edit Permission</h3>
      {msg ? <div className="alert alert-danger">{msg}</div> : null}
      <form onSubmit={onSubmit}>
        <div className="mb-3">
          <label className="form-label">Permission Name</label>
          <input
            type="text"
            name="name"
            className="form-control"
            required
            value={name}
            onChange={(e) => setName(e.target.value)}
          />
        </div>
        <div className="mb-3">
          <label className="form-label">Description</label>
          <textarea
            name="description"
            className="form-control"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            rows={3}
          />
        </div>
        <button type="submit" className="btn btn-primary">
          Update
        </button>
        <Link to={`${ROLE_PERMISSION_BASE}/list_permissions`} className="btn btn-secondary ms-2">
          Cancel
        </Link>
      </form>
    </div>
  )
}
