import React, { useState } from 'react'
import { Button } from '../button/index.js'
import { View } from '../view'
import { Form, FieldFactory, FormStatus } from './index.js'

const dataPreviewStyle = {
  margin: 0,
  padding: 'var(--space-s)',
  background: 'var(--color-secondary)',
  color: 'var(--text-default-color, CanvasText)',
  borderRadius: 'var(--space-xs)',
  border: '1px solid var(--separator-primary)',
  fontSize: 12,
  overflow: 'auto',
}

export default {
  title: 'Design System/Forms/Form',
  component: Form,
  parameters: {
    layout: 'fullscreen',
    docs: {
      story: {
        inline: true,
        height: 'auto',
      },
    },
  },
}

const demoFields = [
  { name: 'firstName', type: 'text', label: 'First name', required: true },
  { name: 'lastName', type: 'text', label: 'Last name', required: true },
  { name: 'email', type: 'email', label: 'Email', required: true },
  { name: 'active', type: 'boolean', label: 'Active' },
]

function FormShell ({ status = [], initial = {} }) {
  const [preview, setPreview] = useState(initial)
  return (
    <View
      surface="primary"
      inset="m"
      roundness="m"
      gap="m"
      style={{ maxWidth: 480, fontFamily: 'system-ui, sans-serif' }}
    >
      <Form
        id="@ossy/storybook/form/demo"
        fields={demoFields}
        defaultData={initial}
        onChange={({ data }) => setPreview(data)}
        onSubmit={data => setPreview(data)}
        status={status}
        gap="m"
      >
        <FieldFactory />
        <Button type="submit" variant="cta">
          Submit
        </Button>
      </Form>
      <pre style={dataPreviewStyle}>{JSON.stringify(preview, null, 2)}</pre>
    </View>
  )
}

export const Default = () => <FormShell />

export const Submitting = () => <FormShell status={[FormStatus.Submitting]} />
