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

import { Icon } from '../../components/Icon';
import { useUsercentrics } from '../../contexts/UsercentricsContext';
import { DecisionsContext, selectDecision } from '../../contexts/DecisionsContext';
import CheckBox from '../CheckBox';

import { StoredInformation } from './StoredInformation';
import { ContentSection, SectionWithTitle } from './ContentSection';
import { getServiceData } from './getServiceData';

export const ContentService = ({ service }: { service: Service }): JSX.Element => {
  const { handlers, settingsLabels } = useUsercentrics();
  const { decisions, updateDecision } = React.useContext(DecisionsContext);
  const [subServices, setSubservices] = React.useState<Service[]>([]);
  const [isSubServicesOpen, setIsSubservicesOpen] = React.useState(false);
  const toggleSubServicesVisibility = () => setIsSubservicesOpen(!isSubServicesOpen);

  React.useEffect(() => {
    const getSubservices = async () => {
      try {
        const subServices = await service.fetchSubServices();
        setSubservices(subServices);
      } catch (error) {
        console.error(error);
      }
    };

    if (service.subServicesLength > 0 && subServices.length === 0) {
      getSubservices();
    }
  }, [service, service.subServicesLength, subServices.length]);

  const handleCheckBoxOnClick = () => {
    updateDecision(service.id, !decisions[service.id].status);
    handlers?.accept([
      {
        serviceId: service.id,
        status: !decisions[service.id].status,
      },
    ]);
  };
  const serviceLabels = settingsLabels?.service;
  const sections = getServiceData(service, serviceLabels);

  return (
    <div className="uc-text-16 uc-mb-6">
      <div className="uc-mb-4">
        <CheckBox
          disabled={service.isEssential}
          onClick={handleCheckBoxOnClick}
          checked={selectDecision(decisions, service.id)?.status}
        >
          <span className="uc-font-semibold">{service.name}</span>
        </CheckBox>
      </div>
      <div className="uc-pl-6">
        <p className="uc-mb-4">{service.description}</p>

        {sections.length > 0 && (
          <div className="uc-mb-6">
            {sections.map((section, index) => (
              <ContentSection key={index} content={section} />
            ))}
          </div>
        )}

        {subServices.length > 0 && (
          <div className="uc-mb-6 uc-p-4 uc-pb-1 uc-bg-blue-50">
            <div className="uc-flex uc-justify-between uc-items-center uc-mb-4 ">
              <h4 className="uc-font-semibold uc-text-18">Subservices</h4>
              <button
                onClick={toggleSubServicesVisibility}
                className="uc-button uc-text-14 uc-flex uc-items-center uc-button--primary uc-button--small"
              >
                <Icon name={isSubServicesOpen ? 'chevronUp' : 'chevronDown'} />
              </button>
            </div>
            <p className="uc-mb-4">{service.description}</p>

            {isSubServicesOpen &&
              subServices.map((service) =>
                getServiceData(service, serviceLabels).map((section, index) => (
                  <ContentSection key={index} content={section} />
                ))
              )}
          </div>
        )}

        {service.deviceStorage?.disclosures && <StoredInformation disclosures={service.deviceStorage.disclosures} />}

        <SectionWithTitle title={settingsLabels?.service.history.title || 'History'}>
          {service.consent.history.map((choice, index: number) => (
            <div className="uc-flex uc-flex-row uc-justify-between" key={index}>
              <div className="uc-flex uc-flex-row uc-items-center">
                <div
                  className={`uc-rounded-full uc-w-4 uc-h-4 uc-mr-2 ${choice.status ? 'uc-bg-success' : 'uc-bg-error'}`}
                />
                <div className="uc-text-14">
                  {choice.status ? settingsLabels?.general.consentGiven : settingsLabels?.general.consentNotGiven}
                </div>
              </div>
              <div className="uc-text-14">{new Date(choice.timestamp).toLocaleString()}</div>
            </div>
          ))}
        </SectionWithTitle>
      </div>
    </div>
  );
};
