import {
  ServiceContainer, useSaveServiceLayout, useServices,
} from '@bthlabs/homehub-core';
import {withRango} from '@bthlabs/rango';
import React from 'react';

import {Dashboard, DashboardItem, DummyWidget} from 'src/main/components';

export const ControlledDashboardContainer = (props) => { // eslint-disable-line no-unused-vars
  const rangoSettings = props.settings;
  const services = useServices();
  const saveServiceLayout = useSaveServiceLayout();

  const onGridLayoutChange = React.useCallback(
    (layout) => {
      layout.forEach((serviceLayout) => {
        saveServiceLayout(serviceLayout.i, {
          x: serviceLayout.x,
          y: serviceLayout.y,
          w: serviceLayout.w,
          h: serviceLayout.h,
        });
      });
    },
    [saveServiceLayout]
  );

  const layout = services.map((service) => {
    const WidgetComponent = service.widgetComponent || DummyWidget;
    return {
      i: service.instance,
      ...service.layout,
      ...(WidgetComponent.layoutConstraints || {}),
    };
  });

  return (
    <Dashboard
      layout={layout}
      readOnly={rangoSettings.READ_ONLY}
      onGridLayoutChange={onGridLayoutChange}
    >
      {services.map((service) => {
        const WidgetComponent = service.widgetComponent || DummyWidget;

        return (
          <div key={service.instance}>
            <ServiceContainer
              instance={service.instance}
              kind={service.kind}
              readOnly={rangoSettings.READ_ONLY}
            >
              {(props) => {
                const settingsViewProps = {
                  ...props.settingsViewProps,
                  settings: rangoSettings,
                };

                return (
                  <DashboardItem
                    {...props}
                    settingsView={WidgetComponent.settingsView}
                    settingsViewProps={settingsViewProps}
                  >
                    {React.createElement(WidgetComponent, {
                      appearance: props.service.characteristics.appearance,
                      service: props.service,
                      serviceState: props.serviceState,
                      setServiceState: props.setServiceState,
                    })}
                  </DashboardItem>
                );
              }}
            </ServiceContainer>
          </div>
        );
      })}
    </Dashboard>
  );
};
ControlledDashboardContainer.displayName = 'DashboardContainer';

export const DashboardContainer = withRango(ControlledDashboardContainer);
