'use client';

import { useCallback, useMemo, useState } from 'react';

import GridButton from '@/components/GridButton/GridButton';
import Icon from '@/components/Icon/Icon';
import SquareButton from '@/components/SquareButton/SquareButton';
import TreeItem from '@/components/TreeItem/TreeItem';
import { Input } from '@/components/UI/Input';
import { Select } from '@/components/UI/Select';

import { useVehicleDeviceStatus, useVehicleList } from '@/queries/map';

import type { ICameraItem } from '@/interfaces/camera';

import type { IVehicle } from '@/types/IVehicle';
import { useForm } from '@/utils/useForm';
import { useStatusesEx } from '@/queries/tables';
import { data, devicesOptions, prepareTree, statusesOptions, typesOptions } from './constants';
import { filterByDevices, filterByStatus } from './utils';

interface IProps {
  setSelectedVehicles: (newData: IVehicle['id'][]) => void;
  selectedVehicles: IVehicle['id'][];
  handleOpenCamera: (data: any) => void;
  cameras: ICameraItem[];
}

const init = {};
const validation = {};

const selectClasses = {
  root: '[&_div]:border-0',
  input: '!p-0 !border-0 [&_div]:text-black !h-auto',
  text: '!text-[16px]',
  dropdown: '!w-[240px] shadow-2xl mt-2 rounded-xl rounded-t-xl [&_li]:px-4 [&_li]:py-3',
};

const MonitoringCard: React.FC<IProps> = ({
  selectedVehicles,
  handleOpenCamera,
  setSelectedVehicles,
  cameras,
}) => {
  const [filter, setFilter] = useState<any>();

  const statuses = useStatusesEx();
  const list = useVehicleList();
  const onlines = useVehicleDeviceStatus();

  const handleSearch = useCallback(async () => {}, []);

  const form = useForm<any>(handleSearch, validation, init);

  const filteredVehicles = useMemo(() => {
    const typeFilter = form.formData['type'] || [];
    const statusFilter = form.formData['status'] || [];
    const deviceFilter = form.formData['device'] || [];

    return list.data?.vehicles
      .filter((el) => typeFilter.length === 0 || typeFilter.includes(el.vehicleType.toString()))
      .filter((el) => statusFilter.length === 0 || filterByStatus(statusFilter, el))
      .filter((el) => deviceFilter.length === 0 || filterByDevices(deviceFilter, el))
      .filter((el) => !form.formData['number'] || el.nm.includes(form.formData['number']));
  }, [statuses.data, form.formData, list.data]);

  const tree = useMemo(
    () =>
      prepareTree({
        list: {
          vehicles: filteredVehicles,
          companys: list.data?.companys || [],
          result: list.data?.result,
        },
        onlines: onlines.data || [],
      }),
    [filteredVehicles, list, onlines],
  );

  return (
    <div className='flex flex-col justify-between gap-4 w-full bg-white rounded-xl p-4 max-w-[430px] shadow-[0px_1px_1px_#AFAFAF33]'>
      <div className='flex flex-col gap-5'>
        <div className='flex items-center w-full gap-4'>
          <Select
            placeholder='Все типы'
            classes={selectClasses}
            withCheckbox
            isMulti
            options={typesOptions}
            onChange={form.handleChangeField('type')}
            value={form.formData['type']}
          />
        </div>
        <Select
          placeholder='Все статусы'
          classes={selectClasses}
          options={statusesOptions}
          withCheckbox
          isMulti
          onChange={form.handleChangeField('status')}
          value={form.formData['status']}
        />
        <Select
          placeholder='Все устройства'
          classes={selectClasses}
          options={devicesOptions}
          withCheckbox
          isMulti
          onChange={form.handleChangeField('device')}
          value={form.formData['device']}
        />
      </div>
      <div className='flex gap-3 '>
        <Input
          placeholder='Поиск'
          className='h-[56px] [&_div]:h-[56px]'
          icon={
            <div className='mx-2 h-full flex justify-center items-center'>
              <Icon src='/images/icons/icon-search.svg' className='w-8 !h-8 text-[#2981B3]' />
            </div>
          }
          onChange={(e) => form.handleChangeField('number')(e.target.value)}
          value={form.formData['number']}
        />
        {/* <SquareButton
            classes={{
              root: 'h-[56px] w-[56px] min-w-[56px] min-h-[56px]',
            }}
          >
            <Icon src='/images/settings.svg' className='h-[32px] w-[32px] text-primary' />
          </SquareButton> */}
      </div>

      <div className='flex flex-col gap-4 flex-1 mb-4 max-h-[750px] overflow-y-auto scrollbar pr-1'>
        {tree.map((item, index) => (
          <TreeItem
            item={item}
            selected={selectedVehicles}
            onChange={setSelectedVehicles}
            handleOpenCamera={handleOpenCamera}
            key={index}
            cameras={cameras}
          />
        ))}
      </div>
      <div className='flex justify-end'>
        <GridButton
          data={data}
          classes={{
            card: 'right-0 bottom-[48px]',
            label: '!max-w-[223px] !min-w-[223px]',
            button: 'w-[64px]',
          }}
        />
      </div>
    </div>
  );
};

export default MonitoringCard;
