import * as React from 'react';
import { Disclosure } from '@usercentrics/cmp-browser-sdk';

import { Icon } from '../../components/Icon';
import { useUsercentrics } from '../../contexts/UsercentricsContext';

const Item = ({
  title,
  children,
}: React.PropsWithChildren<{
  title: string;
}>) => {
  return (
    <div className="uc-w-1/2">
      <span className="uc-mr-1">{title}:</span>
      <span>{children}</span>
    </div>
  );
};

type Props = {
  disclosures: Disclosure[];
};

export const StoredInformation = ({ disclosures }: Props): JSX.Element => {
  const { settings, settingsLabels } = useUsercentrics();
  const [isOpen, setIsOpen] = React.useState(false);
  const toggle = () => setIsOpen(!isOpen);

  if (!settings || disclosures.length === 0) {
    return <></>;
  }

  const labels = settingsLabels?.cookieInformation;

  return (
    <div className="uc-mb-6">
      <div className="uc-flex uc-justify-between uc-items-center uc-mb-4">
        <h4 className="uc-font-semibold uc-mr-4">{labels?.storedInformation}</h4>
        <button onClick={toggle} className="uc-button uc-button--primary uc-button--small">
          <Icon name={isOpen ? 'chevronUp' : 'chevronDown'} />
        </button>
      </div>

      {isOpen &&
        disclosures.map((disclosure, index) => {
          const durationInMonth = disclosure.maxAgeSeconds
            ? Math.floor(disclosure.maxAgeSeconds / (60 * 60 * 24 * 30))
            : 0;

          return (
            <div key={index} className="uc-mb-4 uc-p-4 uc-rounded-sm uc-border uc-border-solid uc-border-swirl">
              <h5 className="uc-font-semibold uc-mb-4">{disclosure.name}</h5>
              <p className="uc-mb-4 uc-text-14">{disclosure.description}</p>
              <div className="uc-flex uc-text-14">
                <Item title={labels?.duration || ''}>{`${durationInMonth} ${
                  durationInMonth > 1 ? labels?.months : labels?.month
                }`}</Item>
                <Item title={labels?.type || ''}>{disclosure.type}</Item>
              </div>
            </div>
          );
        })}
    </div>
  );
};
