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

export function AddPermissionPage() {
  const navigate = useNavigate()
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [msg, setMsg] = useState<string | null>(null)

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

  return (
    <div className="container mt-4">
      <h3>Add 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-success">
          Save
        </button>
        <Link to={`${ROLE_PERMISSION_BASE}/list_permissions`} className="btn btn-secondary ms-2">
          Cancel
        </Link>
      </form>
    </div>
  )
}
