'use client';
import { useMemo, useRef } from 'react';
import { useQuery } from '@tanstack/react-query';
import { CSVLink } from 'react-csv';
import Icon from '@/components/Icon';
import Operations from '@/components/Operations';
import { Button } from '@/components/UI/Button';
import { Checkbox } from '@/components/UI/Checkbox';
import { Input } from '@/components/UI/Input';
import TableLoading from '@/components/UI/Loaders/TableLoading';
import { Select } from '@/components/UI/Select';
import Table, { type TableData, TableDataColumn } from '@/components/UI/Table';
import { allOperations } from '@/pagesComponents/Settings/constants';
import { CompanyService } from '@/services/Settings/CompanyService';
import type { IOption } from '@/types/IOption';

const headHeadings = [
  {
    name: <Checkbox isActive={false} value='all' />,
    key: 'ALL_CHECKBOXES',
    className: '[&_div]:justify-center',
    renderColumn: (_column: TableDataColumn, _rowData: TableData) => {
      return <Checkbox isActive={false} value={'1'} wrapperClassName='justify-center' />;
    },
  },
  {
    name: 'Операции',
    key: 'operations',
    renderColumn: (_column: TableDataColumn, _rowData: TableData) => {
      return <Operations operationKeys={allOperations} />;
    },
  },
  { name: 'Номер', key: 'number' },
  { name: 'Компания', key: 'company' },
  { name: 'Главное отделение', key: 'main_department' },
  { name: 'Принадлежность к региону', key: 'belonging_to_the_region' },
  { name: 'Предприятие', key: 'firm' },
  { name: 'Основной аккаунт', key: 'main_account' },
  { name: 'Код компании', key: 'company_code' },
  { name: 'Operator name', key: 'operator_name' },
  { name: 'Контакт', key: 'contact' },
  { name: 'Телефон', key: 'phone' },
  { name: 'Area', key: 'area' },
  { name: 'Ядерное', key: 'nuclear' },
  { name: 'Юридический телефон', key: 'legal_phone_number' },
  { name: 'Юридический адрес', key: 'legal_address' },
  { name: 'Время обновления', key: 'time_update' },
];

const importExcelHeaders = headHeadings
  .slice(2, headHeadings.length)
  .map((heading) => ({ label: heading.name.toString(), key: heading.key }));

const typeOptions: IOption[] = [
  { label: 'Все', value: 'ALL' },
  { label: 'Компания', value: 'company' },
  { label: 'Контакт', value: 'contact' },
  { label: 'Телефон', value: 'phone' },
  { label: 'Диспетчер', value: 'dispatcher' },
];

const Company = () => {
  const { data, isPending, refetch, isFetching } = useQuery({
    queryKey: ['getCompany'],
    queryFn: () => CompanyService.getCompany(),
  });

  const tableData = useMemo((): TableData[] | undefined => {
    if (data?.data?.infos?.length) {
      const company = data.data.infos;
      return company.map((c, index) => {
        return {
          id: c.id,
          number: index + 1,
          company: c.name,
          main_department: c.parentName || '',
          main_account: c.accountName || '',
        };
      });
    }
  }, [data?.data?.infos]);

  return (
    <div className='flex flex-col gap-6'>
      <div className='flex items-center gap-5'>
        <Select
          placeholder='Выбор типа'
          classes={{ root: 'min-w-[180px]' }}
          options={typeOptions}
        />
        <Input
          placeholder='Задайте четкий запрос'
          wrapperInputClassName='h-[56px] min-w-[283px]'
          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='darkYellow'>Modify Inspect</Button>
        <Button background='green'>Добавить</Button>
        <Button variant='gray_outlined'>
          <CSVLink data={tableData || []} headers={importExcelHeaders} filename='Компания.xlsx'>
            Excel
          </CSVLink>
        </Button>
        <Button variant='gray_outlined'>Импорт Excel</Button>
      </div>

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

export default Company;
