'use client'

import {
  flexRender,
  getCoreRowModel,
  useReactTable,
  createColumnHelper
} from '@tanstack/react-table'
import { useMemo } from 'react'
import { Button } from '@/shared/components/ui/button'
import { Trash2Icon } from 'lucide-react'
import { cn } from '@/shared/lib/utils'
import { Role, type UserGrant } from '../types/user-grant'

const roleLabel = (role: Role) =>
  role === Role.ADMINISTRATOR ? 'Администратор' : 'Менеджер'

const columnHelper = createColumnHelper<UserGrant>()

type Props = {
  data: Array<UserGrant>
  onEdit: (grant: UserGrant) => void
  onDelete: (grant: UserGrant) => void
  isDeletingId: string | null
}

export const UserGrantsDataTable = ({
  data,
  onEdit,
  onDelete,
  isDeletingId
}: Props) => {
  const columns = useMemo(
    () => [
      columnHelper.accessor((row) => row.receiver.fullname, {
        id: 'fullname',
        header: 'Имя',
        cell: (info) => (
          <span className='font-medium'>{info.getValue()}</span>
        )
      }),
      columnHelper.accessor((row) => row.receiver.email, {
        id: 'email',
        header: 'Почта',
        cell: (info) => (
          <span className='text-muted-foreground'>{info.getValue()}</span>
        )
      }),
      columnHelper.accessor((row) => row.grantSites, {
        id: 'role',
        header: 'Роль',
        cell: (info) => {
          const sites = info.getValue()
          if (!sites?.length) {
            return <span className='text-muted-foreground'>—</span>
          }
          const roles = Array.from(new Set(sites.map((gs) => gs.role)))
          return (
            <div className='flex max-w-sm flex-wrap gap-1'>
              {roles.map((role) => (
                <span
                  key={role}
                  className='bg-muted text-foreground/90 rounded-md px-2 py-0.5 text-xs'
                >
                  {roleLabel(role)}
                </span>
              ))}
            </div>
          )
        }
      }),
      columnHelper.accessor((row) => row.grantSites, {
        id: 'sites',
        header: 'Сайты',
        cell: (info) => {
          const sites = info.getValue()
          if (!sites?.length) {
            return <span className='text-muted-foreground'>—</span>
          }
          return (
            <div className='flex max-w-lg flex-wrap gap-1'>
              {sites.map((gs, i) => (
                <span
                  key={`${info.row.original.id}-${gs.site.domain}-${i}`}
                  className='bg-muted text-foreground/90 rounded-md px-2 py-0.5 text-xs'
                  title={gs.site.domain}
                >
                  {gs.site.title}
                </span>
              ))}
            </div>
          )
        }
      }),
      columnHelper.display({
        id: 'actions',
        header: '',
        cell: (info) => (
          <div className='flex flex-wrap items-center justify-end gap-1'>
            <Button
              type='button'
              variant='ghost'
              size='sm'
              className='h-8 px-2 text-xs'
              disabled={isDeletingId === info.row.original.id}
              onClick={() => onEdit(info.row.original)}
            >
              Изменить
            </Button>
            <Button
              type='button'
              variant='ghost'
              size='icon-sm'
              className='text-destructive hover:text-destructive'
              disabled={isDeletingId === info.row.original.id}
              onClick={() => onDelete(info.row.original)}
              aria-label='Удалить выдачу прав'
            >
              <Trash2Icon className='size-4' />
            </Button>
          </div>
        )
      })
    ],
    [onEdit, onDelete, isDeletingId]
  )

  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel()
  })

  return (
    <div className='border-border bg-card overflow-hidden rounded-xl border'>
      <div className='overflow-x-auto'>
        <table className='w-full min-w-[880px] caption-bottom text-sm'>
          <thead className='bg-muted/40 [&_tr]:border-b'>
            {table.getHeaderGroups().map((headerGroup) => (
              <tr key={headerGroup.id} className='border-border border-b'>
                {headerGroup.headers.map((header) => (
                  <th
                    key={header.id}
                    className={cn(
                      'text-foreground h-11 px-3 text-left align-middle font-medium',
                      header.id === 'actions' && 'min-w-[148px]'
                    )}
                  >
                    {header.isPlaceholder
                      ? null
                      : flexRender(
                          header.column.columnDef.header,
                          header.getContext()
                        )}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody className='[&_tr:last-child]:border-0'>
            {table.getRowModel().rows.length === 0 ? (
              <tr>
                <td
                  colSpan={columns.length}
                  className='text-muted-foreground p-6 text-center align-middle'
                >
                  Пока никого не приглашали — добавьте пользователя по почте.
                </td>
              </tr>
            ) : (
              table.getRowModel().rows.map((row) => (
                <tr
                  key={row.id}
                  className='border-border hover:bg-muted/30 border-b transition-colors'
                >
                  {row.getVisibleCells().map((cell) => (
                    <td key={cell.id} className='px-3 py-3 align-middle'>
                      {flexRender(
                        cell.column.columnDef.cell,
                        cell.getContext()
                      )}
                    </td>
                  ))}
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}
