'use client';

import React, { useCallback, useMemo, useState } from 'react';
import classNames from 'clsx';

import Icon from '@/components/Icon';
import { Checkbox } from '@/components/UI/Checkbox';
import { useVehicleDeviceStatus } from '@/queries/map';

import type { ICameraItem } from '@/interfaces/camera';
import type { IVehicle } from '@/types/IVehicle';
import type { ITreeItem } from './interface';

interface IProps {
  item: ITreeItem;
  selected: IVehicle['id'][];
  onChange: (newData: IVehicle['id'][]) => void;
  handleOpenCamera: (data: any) => void;
  cameras: ICameraItem[];
}

const TreeItem: React.FC<IProps> = ({ item, onChange, selected, handleOpenCamera, cameras }) => {
  const [isOpen, setIsOpen] = useState(false);

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

  const handleToggle = useCallback(() => {
    setIsOpen((prev) => {
      return !prev;
    });

    if (item.type === 'camera') {
      handleOpenCamera({
        chnName: item.Channel,
        vehID: item.DevIDNO,
      });
    }
  }, [item, handleOpenCamera]);

  const isActive = useMemo(() => {
    return 'isOnline' in item ? item.isOnline : false;
  }, [item]);

  return (
    <div className={classNames('flex flex-col gap-4', {
      'opacity-25': item.type === 'company' && item.childs?.length === 0
    })}>
      <div className='flex items-center justify-between pr-2'>
        <div className='flex gap-3 cursor-pointer' role='button' onClick={handleToggle}>
          {!item.childs?.length ? (
            <>
              {item.type === 'camera' && (
                <div className='relative'>
                  <Icon
                    src='/images/icons/icon-camera.svg'
                    className={classNames('h-6 w-6', {
                      'text-[#A6A6A6]': !isActive,
                      'text-primary text-opacity-40': isActive,
                      '!text-primary !text-opacity-100': cameras?.some(
                        (el) => item.DevIDNO === el.DevIDNO && item.Channel === el.Channel,
                      ),
                    })}
                  />
                  <div className='border-t absolute left-0 w-1/2 top-1/2 -translate-y-1/2 -translate-x-full' />
                </div>
              )}

              {item.type === 'vehicle' && <div className='h-6 w-6' />}

              {!item.type && <div className='h-6 w-6' />}
            </>
          ) : (
            <div className='h-6 w-6 border-[1px] border-light_gray rounded flex items-center justify-center'>
              {isOpen ? (
                <div className='h-[1px] w-[8px] bg-black' />
              ) : (
                <div className='h-2 w-2 relative'>
                  <div className='h-[1px] w-[8px] bg-black absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2' />
                  <div className='h-[8px] w-[1px] bg-black absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2' />
                </div>
              )}
            </div>
          )}

          <div role='button' onClick={(e) => e.stopPropagation()}>
            {item.type === 'vehicle' && (
              <Checkbox
                label=''
                value=''
                isActive={selected.includes(item.key as unknown as number)}
                onChange={() => {
                  if (selected.includes(item.key as unknown as number)) {
                    onChange(selected.filter((el) => el !== (item.key as unknown as number)));
                  } else {
                    onChange([...selected, item.key as unknown as number]);
                  }
                }}
              />
            )}
          </div>

          <div className='flex items-center gap-2'>
            <span>{item.title}</span>
            {item.type === 'vehicle' && isActive && (
              <div className='relative'>
                <Icon src='/images/icons/icon-camera.svg' className={'h-4 w-4 text-[#A6A6A6]'} />
                <div className='border-t absolute left-0 w-1/2 top-1/2 -translate-y-1/2 -translate-x-full' />
              </div>
            )}
          </div>
        </div>
        {item.type === 'company' && (
          <p className='text-primary font-medium text-base leading-5'>
            {item.childs?.filter((el) => el.isOnline).length}/{item.childs?.length || 0}
          </p>
        )}
      </div>

      {item.childs && isOpen && (
        <div className='pl-3 border-l ml-3 -mt-4 pt-4 flex flex-col gap-4'>
          {item.childs.map((subItem, index) => (
            <TreeItem
              key={index}
              item={subItem}
              selected={selected}
              onChange={onChange}
              handleOpenCamera={handleOpenCamera}
              cameras={cameras}
            />
          ))}
        </div>
      )}
    </div>
  );
};

export default TreeItem;
