/* eslint-disable jsx-a11y/no-redundant-roles */
/* eslint-disable jsx-a11y/no-static-element-interactions */
/* eslint-disable jsx-a11y/click-events-have-key-events */
import { Switch } from '@headlessui/react';
import { useId } from '@radix-ui/react-id';
import { Flow, Prose, Stack, Chain } from '@rasahq/react-tabula/system';
import { ManagerBuilder } from '@rasahq/react-tabula/vendor/segment/manager';
import { Link } from 'app/link';
import clsx from 'clsx';
import { useState } from 'react';

import { MotionDialog } from '../../motion/dialog';
import * as css from './segment-manager.module.scss';

export function SegmentManager({ categories, cdnHost, writeKey, children, ...restProps }) {
  const [isOpen, setIsOpen] = useState(false);
  const dialogId = useId();
  const dialogHeadingID = useId();
  const openDialog = () => setIsOpen(true);
  const closeDialog = () => setIsOpen(false);
  return (
    <ManagerBuilder
      {...{
        categories,
        cdnHost,
        writeKey,
        domain: process.env.NODE_ENV === 'production' ? '.rasa.com' : undefined,
      }}
    >
      {({
        isConsentRequired, // do we need this at all ?
        // haveFlagsChanged, // are there unsaved changes ?
        newDestinations, // list of new destinations since last save
        destinations, // all existing destination
        // destinationFlags, // yes/no choices, by destination
        categories, // all categories, each with `destinationIDs` and other meta data
        categoryFlags, // yes/no choices, by category
        setAllCategoryFlags, // set state of all categories; returns ({ categoryFlags, destinationFlags })
        setCategoryFlag, // set state of one category; returns ({ categoryFlags, destinationFlags })
        // resetFlagsFromCookie, // rebuild ui state based on cookie state
        saveFlagsToCookie, // save cookie state to actual cookie; can receive ({ categoryFlags, destinationFlags })
      }) => {
        const isAlertNeeded = isConsentRequired && newDestinations.length > 0;
        return (
          <>
            <button
              as="button"
              type="button"
              {...restProps}
              onClick={() => {
                openDialog();
              }}
            >
              {children}
            </button>

            {isAlertNeeded && (
              <aside className={clsx(css.banner, 'bg-brand bg-tone-7')}>
                <Prose className="prose-sans-s fg-tone-1">
                  <h2>
                    <span role="img" aria-label="Cookie Consent">
                      🍪
                    </span>
                  </h2>
                  <p>
                    We collect and process your personal information for the following purposes: Visitor
                    Statistics, Browsing Behavior.{' '}
                    <button
                      className={clsx(css.learnMoreLink, 'link')}
                      onClick={() => {
                        setAllCategoryFlags(true); // default to true, when opened from here !
                        openDialog();
                      }}
                    >
                      Learn more...
                    </button>
                  </p>
                  <div>
                    <button
                      className="btn-solid ui-base"
                      onClick={() => {
                        const flags = setAllCategoryFlags(true);
                        saveFlagsToCookie(flags);
                      }}
                    >
                      Agree and Close
                    </button>
                  </div>
                </Prose>
              </aside>
            )}

            <MotionDialog
              className={css.dialog}
              labelledby={dialogHeadingID}
              targetId={dialogId}
              {...{ isOpen }}
              overlayMotion={{ initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 } }}
              contentMotion={{ initial: { y: 20 }, animate: { y: 0 }, exit: { y: 20 } }}
            >
              <Stack gapY={30}>
                <div className="prose-sans-s">
                  <h2 className="font-sans-m" id={'headingID'}>
                    Information that we collect
                  </h2>
                  <p>
                    Here you can see and customize the information that we collect about you. To learn more,
                    please read our{' '}
                    <Link to="/privacy-policy" onClick={closeDialog}>
                      privacy policy
                    </Link>
                  </p>
                </div>
                <Stack as="fieldset" gapY={30}>
                  {categories.map((category) => {
                    const needsReConsent = category.destinationIDs.some((destID) =>
                      newDestinations.some((dest) => dest.id == destID),
                    );
                    const isEnabled = Boolean(categoryFlags[category.id]);
                    return (
                      <Stack gapY={30} key={category.id}>
                        <div>
                          <Switch.Group>
                            <Flow gap={24}>
                              <div>
                                <Switch
                                  checked={isEnabled}
                                  onChange={(bool) =>
                                    setCategoryFlag({
                                      [category.id]: bool,
                                    })
                                  }
                                  className={clsx(css.toggleOuter, { enabled: isEnabled })}
                                >
                                  <span className={clsx(css.toggleInner, { enabled: isEnabled })} />
                                </Switch>
                              </div>
                              <Switch.Label className={clsx(css.toggleLabel, { enabled: isEnabled })}>
                                <span className="font-sans-s fw-bold">{category.name}</span>
                                <span>{isEnabled ? '(enabled)' : '(disabled)'}</span>
                              </Switch.Label>
                            </Flow>
                          </Switch.Group>
                        </div>
                        <p className={clsx(css.toggleDescription, { enabled: isEnabled })}>
                          {category.description} Uses the following services:
                        </p>
                        <ul className={clsx(css.toggleDescription, { enabled: isEnabled })}>
                          {category.destinationIDs.map((id, i, arr) => {
                            const { name: destination } = destinations.find((d) => id === d.id) || {};
                            const isNew = newDestinations.some((d) => id === d.id);
                            return destination ? (
                              <li key={id}>
                                {isNew ? <em>{destination}</em> : destination}
                                {i < arr.length - 1 ? ', ' : ''}
                              </li>
                            ) : null;
                          })}
                        </ul>
                      </Stack>
                    );
                  })}
                </Stack>
                <Chain gap="s" mt="l">
                  <button
                    type="button"
                    className="btn bg-dazzle"
                    onClick={() => {
                      saveFlagsToCookie();
                      closeDialog();
                    }}
                  >
                    Save
                  </button>
                </Chain>
              </Stack>
            </MotionDialog>
          </>
        );
      }}
    </ManagerBuilder>
  );
}
