import React, { useState } from "react";
import {
  FormGroup,
  Select,
  SelectVariant,
  SelectOption,
} from "@patternfly/react-core";
import { useTranslation } from "react-i18next";
import { Controller, useFormContext } from "react-hook-form";

import { useLoginProviders } from "../../context/server-info/ServerInfoProvider";
import { ClientDescription } from "../ClientDescription";
import { FormAccess } from "../../components/form-access/FormAccess";
import { HelpItem } from "../../components/help-enabler/HelpItem";

export const GeneralSettings = () => {
  const { t } = useTranslation("clients");
  const { errors, control } = useFormContext();

  const providers = useLoginProviders();
  const [open, isOpen] = useState(false);

  return (
    <FormAccess isHorizontal role="manage-clients">
      <FormGroup
        label={t("clientType")}
        fieldId="kc-type"
        validated={errors.protocol ? "error" : "default"}
        labelIcon={
          <HelpItem
            helpText="clients-help:clientType"
            forLabel={t("clientType")}
            forID="kc-type"
          />
        }
      >
        <Controller
          name="protocol"
          defaultValue=""
          control={control}
          render={({ onChange, value }) => (
            <Select
              id="kc-type"
              onToggle={() => isOpen(!open)}
              onSelect={(_, value) => {
                onChange(value as string);
                isOpen(false);
              }}
              selections={value}
              variant={SelectVariant.single}
              aria-label={t("selectEncryptionType")}
              isOpen={open}
            >
              {providers.map((option) => (
                <SelectOption
                  selected={option === value}
                  key={option}
                  value={option}
                />
              ))}
            </Select>
          )}
        />
      </FormGroup>
      <ClientDescription />
    </FormAccess>
  );
};
