import { type FormEvent, useEffect, useState } from 'react'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { fetchRole, updateRole } from '../../api/rolePermission'
import { ROLE_PERMISSION_BASE } from './rolePermissionPaths'

function toSlug(str: string) {
  return String(str || '')
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '_')
    .replace(/^_+|_+$/g, '')
}

export function EditRolePage() {
  const { roleId } = useParams<{ roleId: string }>()
  const navigate = useNavigate()
  const [name, setName] = useState('')
  const [slug, setSlug] = useState('')
  const [slugTouched, setSlugTouched] = useState(false)
  const [dashboardRoute, setDashboardRoute] = useState('')
  const [description, setDescription] = useState('')
  const [priority, setPriority] = useState(100)
  const [isActive, setIsActive] = useState(true)
  const [loading, setLoading] = useState(true)
  const [msg, setMsg] = useState<string | null>(null)

  useEffect(() => {
    if (!roleId) return
    fetchRole(roleId)
      .then((d) => {
        const r = d.role
        if (r) {
          setName(String(r.name ?? ''))
          setSlug(String(r.slug ?? ''))
          setDashboardRoute(String(r.dashboard_route ?? ''))
          setDescription(String(r.description ?? ''))
          setPriority(Number(r.priority ?? 100))
          setIsActive(r.is_active === true || r.is_active === 1 || r.is_active === '1')
        }
      })
      .catch(() => setMsg('Could not load role.'))
      .finally(() => setLoading(false))
  }, [roleId])

  async function onSubmit(e: FormEvent) {
    e.preventDefault()
    if (!roleId) return
    setMsg(null)
    try {
      await updateRole(roleId, {
        name: name.toLowerCase(),
        slug: slug || toSlug(name),
        dashboard_route: dashboardRoute.toLowerCase(),
        description: description.toLowerCase(),
        priority,
        is_active: isActive ? 1 : 0,
      })
      navigate(`${ROLE_PERMISSION_BASE}/roles`)
    } catch (err: unknown) {
      setMsg(err instanceof Error ? err.message : 'Update failed.')
    }
  }

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

  return (
    <div className="container-fluid py-5">
      <div className="row justify-content-center">
        <div className="col-xl-6">
          {msg ? <div className="alert alert-danger">{msg}</div> : null}
          <div className="card shadow mb-4">
            <div className="card-header py-3">
              <h6 className="m-0 text-primary">Edit role</h6>
            </div>
            <div className="card-body">
              <form onSubmit={onSubmit}>
                <div className="mb-3">
                  <label className="form-label" htmlFor="roleName">
                    Role name
                  </label>
                  <input
                    id="roleName"
                    className="form-control"
                    minLength={3}
                    maxLength={255}
                    required
                    value={name}
                    onChange={(e) => {
                      const v = e.target.value
                      setName(v)
                      if (!slugTouched) setSlug(toSlug(v))
                    }}
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label" htmlFor="roleSlug">
                    Slug
                  </label>
                  <input
                    id="roleSlug"
                    className="form-control"
                    maxLength={64}
                    value={slug}
                    onChange={(e) => {
                      setSlugTouched(true)
                      setSlug(e.target.value)
                    }}
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label" htmlFor="dashboardRoute">
                    Dashboard route
                  </label>
                  <input
                    id="dashboardRoute"
                    className="form-control"
                    maxLength={255}
                    required
                    value={dashboardRoute}
                    onChange={(e) => setDashboardRoute(e.target.value)}
                    onBlur={(e) => setDashboardRoute(e.target.value.toLowerCase())}
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label" htmlFor="roleDescription">
                    Description
                  </label>
                  <textarea
                    id="roleDescription"
                    className="form-control"
                    rows={3}
                    maxLength={500}
                    value={description}
                    onChange={(e) => setDescription(e.target.value)}
                    onBlur={(e) => setDescription(e.target.value.toLowerCase())}
                  />
                </div>
                <div className="mb-3">
                  <label className="form-label" htmlFor="rolePriority">
                    Priority
                  </label>
                  <input
                    id="rolePriority"
                    type="number"
                    className="form-control"
                    min={0}
                    step={1}
                    required
                    value={priority}
                    onChange={(e) => setPriority(Number(e.target.value))}
                  />
                </div>
                <div className="mb-3 form-check">
                  <input
                    className="form-check-input"
                    type="checkbox"
                    id="roleActive"
                    checked={isActive}
                    onChange={(e) => setIsActive(e.target.checked)}
                  />
                  <label className="form-check-label" htmlFor="roleActive">
                    Active
                  </label>
                </div>
                <div className="d-flex justify-content-between">
                  <Link to={`${ROLE_PERMISSION_BASE}/roles`} className="btn btn-secondary">
                    Cancel
                  </Link>
                  <button type="submit" className="btn btn-primary">
                    Update role
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
