'use client';
import { useQuery } from '@tanstack/react-query';
import { useMemo, useState } from 'react';
import dynamic from 'next/dynamic';
import Icon from '@/components/Icon';
import Operations, { OperationKeys } from '@/components/Operations';
import { Button } from '@/components/UI/Button';
import { Input } from '@/components/UI/Input';
import TableLoading from '@/components/UI/Loaders/TableLoading';
const Modal = dynamic(() => import('@/components/UI/Modal'), { ssr: false });
import Table, { type TableData, TableDataColumn } from '@/components/UI/Table';
import { RoleService } from '@/services/Settings/RoleService';

const operations: OperationKeys = ['watch', 'edit', 'remove'];

const headHeadings = [
  {
    name: 'Операции',
    key: 'operations',
    renderColumn: (_column: TableDataColumn, _rowData: TableData) => {
      return <Operations operationKeys={operations} />;
    },
  },
  { name: 'Номер', key: 'number' },
  { name: 'Название', key: 'name' },
  { name: 'Компания', key: 'company' },
  { name: 'Открытый', key: 'opened' },
];

const Role = () => {
  const [isOpenCreateModal, setIsOpenCreateModal] = useState<boolean>(false);
  const { data, isPending, refetch, isFetching } = useQuery({
    queryKey: ['getRoles'],
    queryFn: () => RoleService.getRoles(),
  });

  const tableData = useMemo((): TableData[] | undefined => {
    if (data?.data.infos?.length) {
      const roles = data.data.infos;
      return roles.map((role, index) => {
        return {
          id: role.id,
          number: index + 1,
          name: role.name,
          company: role?.company?.name || '',
          opened: 'Нет',
        };
      });
    }
  }, [data?.data?.infos]);

  return (
    <>
      <div className='flex flex-col gap-6'>
        <div className='flex items-center gap-5 [&_button]:max-w-max'>
          <Input
            className='w-[283px]'
            placeholder='Название роли/Компании'
            wrapperInputClassName='h-[56px]'
            icon={
              <Icon
                src='/images/icons/icon-search.svg'
                className='size-[21px] min-w-[21px] text-primary mr-4'
              />
            }
          />
          <Button background='black' onClick={() => refetch()}>
            Все роли
          </Button>
          <Button background='green'>Добавить</Button>
          <Button variant='gray_outlined'>Excel</Button>
        </div>

        {isPending ? (
          <TableLoading />
        ) : (
          <Table isLoading={isFetching} headHeadings={headHeadings} data={tableData || []} />
        )}
      </div>

      <Modal isOpen={isOpenCreateModal} closeModal={() => setIsOpenCreateModal(false)}>
        <div>Создание</div>
      </Modal>
    </>
  );
};

export default Role;
