import { memo } from 'react'
import { Pencil, Trash2 } from 'lucide-react'

import type { Employee } from '../../../../entities/employee/model/types'
import {
  getEmployeeFullName,
  getEmployeeRoleLabel,
} from '../../lib/employeeFormatters'

function getUserInitials(employee: Employee) {
  const first = employee.lastName?.trim()[0] ?? ''
  const second = employee.firstName?.trim()[0] ?? ''

  return `${first}${second}`.toUpperCase() || '??'
}

function formatCreatedAt(createdAt?: string) {
  if (!createdAt) return 'Не указана'

  return new Intl.DateTimeFormat('ru-RU', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric',
  }).format(new Date(createdAt))
}

type UsersTableProps = {
  employees: Employee[]
  canManageUsers: boolean
  onEdit: (employee: Employee) => void
  onDelete: (employee: Employee) => void
}

type UserTableRowProps = {
  employee: Employee
  canManageUsers: boolean
  onEdit: (employee: Employee) => void
  onDelete: (employee: Employee) => void
}

const UserTableRow = memo(function UserTableRow({
  employee,
  canManageUsers,
  onEdit,
  onDelete,
}: UserTableRowProps) {
  const login = employee.login ?? employee.username ?? ''

  return (
    <tr className="employees-table__row">
      <td>
        <div className="employee-person">
          <div className={`employee-person__avatar ${employee.avatarUrl ? 'transparent-backdrop' : ''}`}>
            {employee.avatarUrl ? (
              <img src={employee.avatarUrl} alt={getEmployeeFullName(employee)} />
            ) : (
              <span>{getUserInitials(employee)}</span>
            )}
          </div>

          <div className="employee-person__info">
            <span>{getEmployeeFullName(employee) || 'ФИО не указано'}</span>
            <small>ID: {employee.id}</small>
          </div>
        </div>
      </td>

      <td>
        <div className="employee-credentials">
          <span>{employee.email || 'Email не указан'}</span>
          {login && <small>@{login}</small>}
        </div>
      </td>

      <td>
        <span
          className={
            employee.role === 'ADMIN' || employee.role === 'Admin'
              ? 'employee-role employee-role--admin'
              : 'employee-role'
          }
        >
          {getEmployeeRoleLabel(employee.role)}
        </span>
      </td>

      <td>
        <span className="employee-created-at">
          {formatCreatedAt(employee.createdAt)}
        </span>
      </td>

      <td>
        {canManageUsers ? (
          <div className="employees-table-actions">
            <button
              className="employees-action-btn employees-action-btn--edit"
              type="button"
              onClick={(event) => {
                event.stopPropagation()
                onEdit(employee)
              }}
            >
              <Pencil size={16} />
              Редактировать
            </button>

            <button
              className="employees-action-btn employees-action-btn--delete"
              type="button"
              onClick={(event) => {
                event.stopPropagation()
                onDelete(employee)
              }}
            >
              <Trash2 size={16} />
              Удалить
            </button>
          </div>
        ) : (
          <span className="employees-table-actions__muted">
            Только просмотр
          </span>
        )}
      </td>
    </tr>
  )
})

export const UsersTable = memo(function UsersTable({
  employees,
  canManageUsers,
  onEdit,
  onDelete,
}: UsersTableProps) {
  return (
    <table className="employees-table">
      <thead>
        <tr>
          <th>ФИО</th>
          <th>Логин / email</th>
          <th>Роль</th>
          <th>Дата создания</th>
          <th>Действия</th>
        </tr>
      </thead>

      <tbody>
        {employees.map((employee) => (
          <UserTableRow
            key={employee.id}
            employee={employee}
            canManageUsers={canManageUsers}
            onEdit={onEdit}
            onDelete={onDelete}
          />
        ))}
      </tbody>
    </table>
  )
})
