import { GroupField as GroupFieldType, SchemaFieldProps } from '@vev/utils';
import React, { useState } from 'react';
import { SilkeBox } from '../../silke-box';
import { SilkeIcon } from '../../silke-icon';
import { SilkeText, SilkeTextSmall } from '../../silke-text';
import { SilkeSchemaFields } from '../silke-schema-fields';

/** Collapsible card section. Renders a clickable header with chevron inside a surface-1 card. */
export default function GroupField({
  value = {},
  schema,
  disabled,
  readonly,
}: SchemaFieldProps<GroupFieldType>) {
  const [collapsed, setCollapsed] = useState(schema.options?.collapsed ?? false);

  return (
    <SilkeBox column flex vPad="xs">
      <SilkeBox column bg="surface-1" rounded="small" hPad="s" vPad="s" gap="s">
        <SilkeBox vAlign="center" cursor="pointer" onClick={() => setCollapsed((c) => !c)}>
          <SilkeBox flex>
            <SilkeTextSmall weight="strong">{schema.title || schema.name}</SilkeTextSmall>
          </SilkeBox>
          <SilkeBox
            size="s"
            align="center"
            style={{
              transform: collapsed ? 'rotate(-90deg)' : 'rotate(0deg)',
              transition: 'transform 150ms ease',
            }}
          >
            <SilkeTextSmall>
              <SilkeIcon icon="chevron.down" />
            </SilkeTextSmall>
          </SilkeBox>
        </SilkeBox>
        {!collapsed && (
          <SilkeSchemaFields
            schema={schema.fields}
            value={value}
            disabled={disabled}
            readonly={readonly}
            noPad
          />
        )}
      </SilkeBox>
    </SilkeBox>
  );
}
