import {
  Button,
  DataList,
  DataListAction,
  DataListCell,
  DataListItem,
  DataListItemCells,
  DataListItemRow,
  Dropdown,
  DropdownItem,
  KebabToggle,
  PageSection,
  Spinner,
  Split,
  SplitItem,
  Title,
} from "@patternfly/react-core";
import { CSSProperties, useState } from "react";
import { Trans, useTranslation } from "react-i18next";
import { getCredentials } from "../api/methods";
import {
  CredentialContainer,
  CredentialMetadataRepresentation,
} from "../api/representations";
import { EmptyRow } from "../components/datalist/EmptyRow";
import { Page } from "../components/page/Page";
import { TFuncKey } from "../i18n";
import { formatDate } from "../utils/formatDate";
import { usePromise } from "../utils/usePromise";
import { useEnvironment } from "../root/KeycloakContext";

type MobileLinkProps = {
  title: string;
  onClick: () => void;
  testid?: string;
};

const MobileLink = ({ title, onClick, testid }: MobileLinkProps) => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <Dropdown
        isPlain
        position="right"
        toggle={<KebabToggle onToggle={setOpen} />}
        className="pf-u-display-none-on-lg"
        isOpen={open}
        dropdownItems={[
          <DropdownItem key="1" onClick={onClick}>
            {title}
          </DropdownItem>,
        ]}
      />
      <Button
        variant="link"
        onClick={onClick}
        className="pf-u-display-none pf-u-display-inline-flex-on-lg"
        data-testid={testid}
      >
        {title}
      </Button>
    </>
  );
};

export const SigningIn = () => {
  const { t } = useTranslation();
  const context = useEnvironment();
  const { login } = context.keycloak;

  const [credentials, setCredentials] = useState<CredentialContainer[]>();

  usePromise(
    (signal) => getCredentials({ signal, context }),
    setCredentials,
    [],
  );

  const credentialRowCells = (
    credMetadata: CredentialMetadataRepresentation,
  ) => {
    const credential = credMetadata.credential;
    const maxWidth = { "--pf-u-max-width--MaxWidth": "300px" } as CSSProperties;
    const items = [
      <DataListCell
        key="title"
        data-testrole="label"
        className="pf-u-max-width"
        style={maxWidth}
      >
        {credential.userLabel || t(credential.type as TFuncKey)}
      </DataListCell>,
    ];

    if (credential.createdDate) {
      items.push(
        <DataListCell
          key={"created" + credential.id}
          data-testrole="created-at"
        >
          <Trans i18nKey="credentialCreatedAt">
            <strong className="pf-u-mr-md"></strong>
            {{ date: formatDate(new Date(credential.createdDate)) }}
          </Trans>
        </DataListCell>,
      );
    }
    return items;
  };

  if (!credentials) {
    return <Spinner />;
  }

  const credentialUniqueCategories = [
    ...new Set(credentials.map((c) => c.category)),
  ];

  return (
    <Page title={t("signingIn")} description={t("signingInDescription")}>
      {credentialUniqueCategories.map((category) => (
        <PageSection key={category} variant="light" className="pf-u-px-0">
          <Title headingLevel="h2" size="xl" id={`${category}-categ-title`}>
            {t(category as TFuncKey)}
          </Title>
          {credentials
            .filter((cred) => cred.category == category)
            .map((container) => (
              <>
                <Split className="pf-u-mt-lg pf-u-mb-lg">
                  <SplitItem>
                    <Title
                      headingLevel="h3"
                      size="md"
                      className="pf-u-mb-md"
                      data-testid={`${container.type}/help`}
                    >
                      <span
                        className="cred-title pf-u-display-block"
                        data-testid={`${container.type}/title`}
                      >
                        {t(container.displayName as TFuncKey)}
                      </span>
                    </Title>
                    <span data-testid={`${container.type}/help-text`}>
                      {t(container.helptext as TFuncKey)}
                    </span>
                  </SplitItem>
                  {container.createAction && (
                    <SplitItem isFilled>
                      <div className="pf-u-float-right">
                        <MobileLink
                          onClick={() =>
                            login({
                              action: container.createAction,
                            })
                          }
                          title={t("setUpNew", {
                            name: t(
                              `${container.type}-display-name` as TFuncKey,
                            ),
                          })}
                          testid={`${container.type}/create`}
                        />
                      </div>
                    </SplitItem>
                  )}
                </Split>

                <DataList
                  aria-label="credential list"
                  className="pf-u-mb-xl"
                  data-testid={`${container.type}/credential-list`}
                >
                  {container.userCredentialMetadatas.length === 0 && (
                    <EmptyRow
                      message={t("notSetUp", {
                        name: t(container.displayName as TFuncKey),
                      })}
                      data-testid={`${container.type}/not-set-up`}
                    />
                  )}

                  {container.userCredentialMetadatas.map((meta) => (
                    <DataListItem key={meta.credential.id}>
                      <DataListItemRow id={`cred-${meta.credential.id}`}>
                        <DataListItemCells
                          className="pf-u-py-0"
                          dataListCells={[
                            ...credentialRowCells(meta),
                            <DataListAction
                              key="action"
                              id={`action-${meta.credential.id}`}
                              aria-label={t("updateCredAriaLabel")}
                              aria-labelledby={`cred-${meta.credential.id}`}
                            >
                              {container.removeable ? (
                                <Button
                                  variant="danger"
                                  onClick={() => {
                                    login({
                                      action:
                                        "delete_credential:" +
                                        meta.credential.id,
                                    });
                                  }}
                                >
                                  {t("delete")}
                                </Button>
                              ) : (
                                <Button
                                  variant="secondary"
                                  onClick={() => {
                                    if (container.updateAction)
                                      login({ action: container.updateAction });
                                  }}
                                  data-testrole="update"
                                >
                                  {t("update")}
                                </Button>
                              )}
                            </DataListAction>,
                          ]}
                        />
                      </DataListItemRow>
                    </DataListItem>
                  ))}
                </DataList>
              </>
            ))}
        </PageSection>
      ))}
    </Page>
  );
};

export default SigningIn;
