'use client';

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

import SquareButton from '@/components/SquareButton';
import GridButton from '@/components/GridButton';
import Icon from '@/components/Icon';

import { useFullWindowContext } from '@/contexts/FullWindowComponentContext';
import { data } from './constants';

interface IProps {
  size: number;
  handleOpenCamera?: (data: any) => void;
  children?: React.ReactNode[];
}

const CameraGrid: React.FC<IProps> = ({ size = 1, children, handleOpenCamera = () => null }) => {
  const ref = useRef<HTMLDivElement>(null);
  const [selectedCameraIndex, setSelectedCameraIndex] = useState<null | number>(null);
  const { handleToggleComponent } = useFullWindowContext();

  const handleSelect = useCallback((index: number) => {
    setSelectedCameraIndex((prev) => (prev === index ? null : index));
  }, []);

  const handleCloseCamera = (index: number) => {
    const camera = cameras?.[index];
    if (React.isValidElement(camera)) {
      const { chnID, deviceID } = camera.props;
      handleOpenCamera({
        chnName: chnID,
        vehID: deviceID,
      });
    }
  };

  const cameras = useMemo(() => {
    return children || [];
  }, [children]);

  const handleSound = useCallback(
    (cellIndex: number) => () => {
      console.log(cameras[cellIndex] as any);
    },
    [cameras],
  );

  return (
    <div
      className='w-full h-full grid rounded-xl overflow-hidden bg-[#222] relative'
      style={{
        gridTemplateColumns: `repeat(${size}, 1fr)`,
        gridTemplateRows: `repeat(${size}, 1fr)`,
      }}
      ref={ref}
    >
      {[...new Array(size * size)].map((_, cellIndex) => (
        <div
          key={cellIndex}
          className={classNames('w-full h-full relative', {
            '!absolute !top-0 !right-0 !bottom-0 !left-0 !z-10': selectedCameraIndex === cellIndex,
          })}
        >
          {cameras?.[cellIndex]}

          <div className='absolute z-[5] p-2 top-0 bottom-0 left-0 right-0 flex flex-col justify-between border-[#2E2F30] active:border-[#2CA32A] border-[0.5px] pointer-events-none'>
            <div className='flex justify-between items-center'>
              {!cameras?.[cellIndex] && (
                <div className='flex gap-[6px]'>
                  {/* {type === 'stream' && <div onClick={handlePlay}><Icon src='/images/play.svg' className='w-6 h-6 text-white' /></div>} */}
                  <Icon src='/images/sound.svg' className='w-6 h-6 text-white' />
                  <Icon src='/images/camera.svg' className='w-6 h-6 text-white' />
                </div>
              )}

              {cameras?.[cellIndex] && (
                <div
                  className='cursor-pointer absolute right-1 top-1 z-50'
                  role='button'
                  onClick={() => handleCloseCamera(cellIndex)}
                >
                  <Icon src='/images/close.svg' className='w-6 h-6 text-white' />
                </div>
              )}
            </div>

            <div className='flex justify-end'>
              <div
                onClick={() => handleSelect(cellIndex)}
                className='cursor-pointer pointer-events-auto'
              >
                <Icon
                  src={
                    cellIndex === cellIndex
                      ? '/images/full-screen.svg'
                      : '/images/icons/icon-video-hide.svg'
                  }
                  className='w-6 h-6 text-white'
                />
              </div>
            </div>
          </div>
        </div>
      ))}

      <div className='absolute bottom-[12px] left-[12px] flex gap-3'>
        <GridButton
          data={data}
          classes={{
            card: 'left-0 bottom-[48px]',
          }}
        />
        <SquareButton
          classes={{
            root: 'h-[40px] w-[40px]',
          }}
          onClick={() => handleToggleComponent(<CameraGrid size={3}>{children}</CameraGrid>)}
        >
          <Icon src='/images/full.svg' className='h-[24px] w-[24px] text-primary' />
        </SquareButton>
      </div>
    </div>
  );
};

export default CameraGrid;
