import React, { useState } from 'react';
import { EventField as EventFieldType, SchemaFieldProps, VevContentEvent } from '@vev/utils';
import { SilkeBox } from '../../silke-box';
import { SilkeTextSmall } from '../../silke-text';
import { SilkeAlertBanner } from '../../silke-alert-banner';
import { SilkeTag } from '../../silke-tag';
import { SilkeIcon } from '../../silke-icon';
import ObjectField from './object-field';

const headerStyle = {
  cursor: 'pointer',
  fontWeight: '600',
  alignItems: 'center',
};

const EventField = ({
  value = [],
  onChange,
  context,
  disabled,
  readonly,
}: SchemaFieldProps<EventFieldType>) => {
  const [toggle, setToggle] = useState(false);

  const pageEvents = context.events?.filter((event) => event.page === context.currentPage?.key);
  const otherEvents = context.events?.filter(
    (event) => event.page !== context.currentPage?.key || !event.page,
  );

  const renderEvents = (events: VevContentEvent[]) => {
    const grouped = events.reduce(
      (res, curr) => {
        const { key } = curr.content;
        if (!res[key]) res[key] = [];
        res[key].push(curr);
        return res;
      },
      {} as { [key: string]: VevContentEvent[] },
    );

    return Object.keys(grouped).map((key, i) => {
      const name = events.find((e) => e.content.key === key)?.content?.name;
      return (
        <SilkeBox column key={key} gap="s">
          <SilkeTextSmall weight="strong">{name}</SilkeTextSmall>
          <SilkeBox column gap="s">
            {grouped[key].map((event, i) => {
              const curr = `${event.content.key}:${event.type}`;
              return (
                <SilkeBox column key={curr}>
                  <SilkeBox gap="s" style={{ border: '1px solid #222' }}>
                    <SilkeTag
                      label={event.type}
                      style={{ cursor: 'pointer' }}
                      color={value.find((e) => e.key === curr) ? 'green' : 'dark'}
                      onClick={() => {
                        if (value.find((e) => e.key === curr)) {
                          return onChange(value.filter((v) => v.key !== curr));
                        }
                        onChange([...value, { key: curr }]);
                      }}
                    ></SilkeTag>
                    <SilkeBox column>
                      <SilkeBox> {event.description}</SilkeBox>
                      {value.find((v) => v.key === curr) && event.args && (
                        <SilkeBox vPad>
                          <ObjectField
                            disabled={disabled}
                            readonly={readonly}
                            schema={{
                              fields: event.args,
                              type: 'object',
                              name: 'args',
                              title: 'Arguments',
                            }}
                            value={value.find((v) => v.key === curr)?.args}
                            onChange={(val) => {
                              const currIndex = value.map((v) => v.key).indexOf(curr);
                              value[currIndex] = {
                                key: curr,
                                args: val,
                              };
                              currIndex >= 0 && onChange(value);
                            }}
                            label="Arguments"
                            context={context}
                          />
                        </SilkeBox>
                      )}
                    </SilkeBox>
                  </SilkeBox>
                </SilkeBox>
              );
            })}
          </SilkeBox>
        </SilkeBox>
      );
    });
  };

  return (
    <SilkeBox flex column gap="m">
      {pageEvents?.length ? (
        <SilkeBox column gap="m">
          <SilkeBox style={headerStyle}>Events on current page</SilkeBox>
          {renderEvents(pageEvents)}
          {otherEvents?.length && (
            <SilkeBox column gap="m">
              <SilkeBox onClick={() => setToggle(!toggle)} style={headerStyle}>
                Events on other pages{' '}
                <SilkeIcon
                  icon={!toggle ? 'caret.up' : 'caret.down'}
                  style={{ marginLeft: '6px' }}
                />
              </SilkeBox>
              {toggle && renderEvents(otherEvents)}
            </SilkeBox>
          )}
        </SilkeBox>
      ) : (
        <SilkeAlertBanner
          kind="warning"
          title="No events in this projects"
          subtitle="Add widgets with events to be able to select an event"
        />
      )}
    </SilkeBox>
  );
};

export default EventField;
