import React, { useEffect, useMemo, useState } from 'react';
import {
  TextButton,
  Box,
  Button,
  Card,
  CardProps,
  Layout,
} from '@wix/design-system';
import { observer } from 'mobx-react-lite';
import { useWixPatternsContainer, usePageContext } from '@wix/bex-core/react';
import { SidePanelsState } from '../../state/SidePanelsState';
import { CustomColumnsEntityPageState } from '../../state/CustomColumnsEntityPageState';
import { CustomColumnsEntityPagePanelMount } from '../CustomColumnsPanel/CustomColumnsEntityPagePanelMount';
import { useSchemaContext } from '../../providers/SchemaContext';
import { CustomColumnsDragAndDrop } from '../CustomColumns/CustomColumnsDragAndDrop';
import { SchemaCardState } from '../../state/SchemaCard/SchemaCardState';
import { Add } from '@wix/wix-ui-icons-common';

export interface SchemaCardProps extends Omit<CardProps, 'children'> {
  title: string;
  subtitle?: string;
  renderField: (fieldId: string) => React.ReactNode;
}

function _SchemaCard({
  title,
  subtitle,
  renderField,
  ...rest
}: SchemaCardProps) {
  const container = useWixPatternsContainer();
  const { translate: t } = container;
  const { modalsContainerRef } = usePageContext();
  const schemaContext = useSchemaContext();
  const schema = schemaContext?.schema;

  const fields = useMemo(
    () =>
      schema
        ? Object.keys(schema.fields)
            .filter((id) => schema.fields[id])
            .map((id) => ({ id }))
        : [],
    [schema?.fields],
  );

  const [schemaCardState] = useState(() =>
    schema && fields.length > 0
      ? new SchemaCardState({
          fields,
          persistencyKey: schema.id,
          container,
        })
      : null,
  );

  useEffect(() => schemaCardState?.init(), []);

  const fieldsState = schemaCardState?.fieldsState;

  const state = useMemo(() => {
    if (!fieldsState || !schema) {
      return null;
    }
    const panels = new SidePanelsState({
      container,
      panelGroupName: 'entity-page',
    });
    return new CustomColumnsEntityPageState({
      container,
      panels,
      fieldsState,
      schema,
      showFieldTypeIcons: true,
      dragAndDrop: CustomColumnsDragAndDrop,
      modalsContainerRef,
    });
  }, [fieldsState, schema]);

  return (
    <Card {...rest}>
      <Card.Header
        title={title}
        subtitle={subtitle}
        suffix={
          state ? (
            <Button
              size="small"
              priority="secondary"
              dataHook="schema-card-manage-fields-button"
              onClick={() => state.panels.toggleSidePanel('customColumns')}
            >
              {t('cairo.table.manage-fields.button.cta')}
            </Button>
          ) : undefined
        }
      />
      <Card.Divider />
      <Card.Content>
        <Layout>
          {fieldsState &&
            fieldsState.orderedFields
              .filter((f) => fieldsState.isFieldVisible(f.id))
              .map((f) => renderField(f.id))}
        </Layout>
      </Card.Content>
      {schemaContext?.addField && (
        <Box padding="SP4" boxSizing="border-box" width="100%">
          <TextButton
            dataHook="schema-card-add-field"
            onClick={schemaContext.addField}
            prefixIcon={<Add />}
          >
            {t('cairo.customFields.addCustomField.CTA')}
          </TextButton>
        </Box>
      )}
      {state && <CustomColumnsEntityPagePanelMount state={state} />}
    </Card>
  );
}

_SchemaCard.displayName = 'SchemaCard';

export const SchemaCard = observer(_SchemaCard);
