import { createResource, mergeProps } from "solid-js";
import List from "../../components/list";
import ShowRegistrationCodeModal from "../../modals/show-registration-code-modal";
import DeleteIntegrationModal from "../../modals/delete-integration-modal";
import DeviceService from "../../services/device-service";

function IntegrationListView(props) {
  props = mergeProps(
    {
      onIntegrationClicked: () => {},
    },
    props
  );
  const [integrations, { refetch: refetchIntegrations }] = createResource(
    DeviceService.getIntegrations,
    { initialValue: [] }
  );

  function handleRegisterIntegration() {
    ShowRegistrationCodeModal.Handler.show();
  }

  DeleteIntegrationModal.onIntegrationDeleted(() => {
    refetchIntegrations();
  });

  function handleDeleteIntegration(integration) {
    DeleteIntegrationModal.setIntegration(integration);
    DeleteIntegrationModal.Handler.show();
  }

  function handleIntegrationItemClicked(item) {
    props.onIntegrationClicked(item.integration);
  }

  return (
    <div
      class={
        "d-flex flex-column overflow-hidden flex-fill px-3 pb-2 pt-3 " +
        props.class
      }
    >
      <div class="d-flex flex-row">
        {props.navigation}
        <div class="d-flex flex-row justify-content-end flex-fill">
          <button
            class="btn btn-dark me-2 mb-3"
            onClick={handleRegisterIntegration}
          >
            <i class="bi bi-plus-square me-2"></i>
            Register
          </button>
        </div>
      </div>
      <List
        onListItemClick={handleIntegrationItemClicked}
        items={integrations().map((integration) => ({
          id: {
            html: <span class="font-monospace">{integration.getId()}</span>,
          },
          name: {
            text: integration.getName(),
          },
          options: {
            html: (
              <>
                <button
                  class="btn btn-sm btn-outline-secondary me-2"
                  onClick={(event) => {
                    event.stopPropagation();
                    handleDeleteIntegration(integration);
                  }}
                >
                  <i class="bi bi-trash-fill"></i>
                </button>
              </>
            ),
          },
          integration: integration,
        }))}
        class={"flex-fill"}
        columns={[
          {
            id: "id",
            name: "id",
            width: 6,
          },
          {
            id: "name",
            name: "Name",
          },
          {
            id: "options",
            name: "",
            width: 4,
          },
        ]}
      ></List>
    </div>
  );
}

export default IntegrationListView;
