'use client';
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import dynamic from 'next/dynamic';
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 { Select } from '@/components/UI/Select';
import Table, { TableData, TableDataColumn } from '@/components/UI/Table';
import TableLoading from '@/components/UI/Loaders/TableLoading';
import { TransportService } from '@/services/Settings/TransportService';
import { allOperations } from '@/pagesComponents/Settings/constants';
import { statisHeadHeadings, statusesOptions, typeOptions } from './constants';
const Modal = dynamic(() => import('@/components/UI/Modal'), { ssr: false });
import TransportViewModal from './components/TransportViewModal';
import AddTransportModal from './components/AddTransportModal';
import FastAddTransportModal from './components/FastAddTransportModal';

const Settings = () => {
  const [selectedTransportIdForWatch, setSelectedTransportIdForWatch] = useState<number | null>(
    null,
  );
  const [isOpenAddModal, setIsOpenAddModal] = useState<boolean>(false);
  const [isOpenFastAddModal, setIsOpenFastAddModal] = useState<boolean>(false);

  const { data, isPending, refetch, isFetching } = useQuery({
    queryKey: ['transport'],
    queryFn: () => TransportService.getTransports(),
  });

  const tableData = useMemo((): undefined | TableData[] => {
    if (!data?.data?.infos?.length) return;
    const transports = data.data.infos;
    return transports.map((transport, index) => {
      return {
        id: transport.id,
        gos_number: transport.vid,
        number: index + 1,
        sim_card_number: transport.devList?.[0].simInfo || '',
        transport_type: '',
        transport_model: '',
        number_color: 'Жёлтый',
        device_no: transport.devList?.[0].name || '',
        serial_number: '',
        last_online_visit: transport.tm,
        installation_date: transport.itm,
        service_end_date: 'No service',
        status: 'Нормально, в сети',
        company: transport.com?.companyName || '',
        convoy: transport.com?.name || '',
        driver_name: '',
      };
    });
  }, [data?.data?.infos]);

  const headHeadings = useMemo(() => {
    return [
      {
        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: (_: TableDataColumn, rowData: TableData) => {
          return (
            <Operations
              operationKeys={allOperations}
              actions={{
                onWatch: () => {
                  setSelectedTransportIdForWatch(rowData.id as number);
                },
              }}
            />
          );
        },
      },
      ...statisHeadHeadings,
    ];
  }, []);

  const isModalOpen = !!selectedTransportIdForWatch || isOpenAddModal || isOpenFastAddModal;

  return (
    <>
      <div className='flex flex-col gap-6'>
        <div className='flex items-center'>
          <div className='flex items-center gap-5'>
            <Select placeholder='Выбор статуса' options={statusesOptions} />
            <Select placeholder='Выбор компании' />
          </div>

          <p className='mr-[10px] ml-[30px]'>Выбор установки:</p>

          <div className='flex items-center gap-5'>
            <Input placeholder='Начало установки' wrapperInputClassName='h-[56px]' />
            <Input placeholder='Конец установки' wrapperInputClassName='h-[56px]' />
            <Select placeholder='Выбор типа' options={typeOptions} />
            <Input
              placeholder='Задайте чёткий запрос'
              wrapperInputClassName='h-[56px]'
              icon={
                <Icon
                  src='/images/icons/icon-search.svg'
                  className='size-[21px] min-w-[21px] text-primary mr-4'
                />
              }
            />
          </div>
        </div>

        <div className='flex items-center gap-[9px]'>
          <Button
            background='blue'
            className='!min-w-[250px] min-h-[68px]'
            onClick={() => refetch()}
          >
            Все транспортные средства
          </Button>
          <Button
            background='green'
            className='min-h-[68px] !min-w-[150px]'
            onClick={() => setIsOpenFastAddModal(true)}
          >
            Быстрое добавление
          </Button>
          <Button
            background='green'
            className='min-h-[68px] !min-w-[115px]'
            onClick={() => setIsOpenAddModal(true)}
          >
            Добавить
          </Button>
          <Button background='green' className='min-h-[68px] !min-w-[150px]'>
            Добавить груз
          </Button>
          <Button background='orange' className='min-h-[68px] !min-w-[150px]'>
            Изменить компанию
          </Button>
          <Button background='red' className='min-h-[68px] !min-w-[110px]'>
            Удалить
          </Button>

          <Button variant='gray_outlined' className='min-h-[68px] !min-w-[150px]'>
            Импорт Excel
          </Button>
          <Button variant='gray_outlined' className='min-h-[68px] !min-w-[150px]'>
            Настройка экспорта
          </Button>
          <Button variant='gray_outlined' className='min-h-[68px] !min-w-[150px]'>
            Настройка импорта
          </Button>
        </div>

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

      <Modal
        isOpen={isModalOpen}
        closeModal={() => {
          setSelectedTransportIdForWatch(null);
          setIsOpenAddModal(false);
          setIsOpenFastAddModal(false);
        }}
        title={isOpenAddModal || isOpenFastAddModal ? 'Добавить транспортное средство' : undefined}
        className={
          isOpenAddModal ? 'max-w-[1464px]' : isOpenFastAddModal ? 'max-w-[744px]' : undefined
        }
        bodyClassName={isOpenAddModal ? '!p-0' : undefined}
      >
        {selectedTransportIdForWatch && (
          <TransportViewModal transportId={selectedTransportIdForWatch} />
        )}
        {isOpenAddModal && <AddTransportModal onClose={() => setIsOpenAddModal(false)} />}
        {isOpenFastAddModal && (
          <FastAddTransportModal onClose={() => setIsOpenFastAddModal(false)} />
        )}
      </Modal>
    </>
  );
};

export default Settings;
