import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { ApiHttpError } from '../../api/http'
import { fetchPermissionsList, type PermissionRow } from '../../api/rolePermission'
import { ROLE_PERMISSION_BASE } from './rolePermissionPaths'

export function PermissionsListPage() {
  const [rows, setRows] = useState<PermissionRow[]>([])
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    fetchPermissionsList()
      .then((d) => setRows(d.permissions ?? []))
      .catch((e: unknown) =>
        setError(e instanceof ApiHttpError ? e.message : 'Unable to load permissions.'),
      )
  }, [])

  return (
    <div className="container-fluid py-3">
      <h2 className="text-center mt-4 mb-3">List of Permissions</h2>

      {error ? <div className="alert alert-danger">{error}</div> : null}

      <div className="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
        <small className="text-muted">Total: {rows.length}</small>
        <div className="d-flex gap-2">
          <Link to={`${ROLE_PERMISSION_BASE}/permissions/create`} className="btn btn-success">
            Add New Permission
          </Link>
          <Link to={`${ROLE_PERMISSION_BASE}/roles`} className="btn btn-secondary">
            Back to Roles
          </Link>
        </div>
      </div>

      <div className="table-responsive">
        <table className="table table-bordered table-striped align-middle">
          <thead className="table-dark">
            <tr>
              <th style={{ width: 90 }}>ID</th>
              <th style={{ width: 280 }}>Name</th>
              <th>Description</th>
              <th style={{ width: 180 }}>Created</th>
              <th style={{ width: 180 }}>Updated</th>
              <th style={{ width: 220 }}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 ? (
              <tr>
                <td colSpan={6} className="text-center text-muted py-4">
                  {error ? '—' : 'No permissions.'}
                </td>
              </tr>
            ) : (
              rows.map((p) => (
                <tr key={String(p.id)}>
                  <td>{String(p.id ?? '')}</td>
                  <td>{String(p.name ?? '')}</td>
                  <td>{String(p.description ?? '')}</td>
                  <td>{String(p.created_at ?? '')}</td>
                  <td>{String(p.updated_at ?? '')}</td>
                  <td>
                    <Link
                      to={`${ROLE_PERMISSION_BASE}/permissions/${p.id}/edit`}
                      className="btn btn-sm btn-primary"
                    >
                      Edit
                    </Link>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
