import React from 'react';
import { usePassport } from '@sensoro/core';
import SelectDeviceModal, { Data } from './select-device-modal';
import SelectDevice from '../select-device';
import MapDeviceInject from '../map-device-inject';
import { useModal } from '@pansy/hooks';
import { filter } from 'lodash';

interface MapDeviceProps {
  className?: string;
  style?: React.CSSProperties;
  relatedCameraIds?: string[];
  value?: string[];
  onChange?: (value: string[]) => void;
  deviceKey?: string;
}

const MapDevice: React.FC<MapDeviceProps> = props => {
  const {
    className,
    style,
    relatedCameraIds,
    value,
    onChange,
    deviceKey = 'cid',
    ...rest
  } = props;
  const { visible, initValue, openModal, closeModal } = useModal<Data>();

  const { merchant } = usePassport();
  return (
    <div>
      <MapDeviceInject {...rest}>
        {(devices: any[], props: any) => (
          <>
            <SelectDevice
              {...props}
              zoom={13}
              center={merchant?.lnglat}
              devices={filter(
                devices,
                item => value && value.indexOf(item[deviceKey]) > -1,
              )}
              className={className}
              style={style}
              value={value}
              onSelectDeviceClick={() =>
                openModal({
                  devices: devices,
                  relatedCameraIds: value,
                })
              }
            />
            <SelectDeviceModal
              deviceKey={deviceKey}
              visible={visible}
              onCancel={() => closeModal()}
              onChange={onChange}
              data={initValue}
            />
          </>
        )}
      </MapDeviceInject>
    </div>
  );
};

export default MapDevice;
