import { useEffect, useState } from 'react'
import { FormErrors } from './index.js'
import { Button } from '../Button/index.js'
import { Form } from './Form.js'
import { Badge } from '../Badge/index.js'
import { Sidebar } from '../Sidebar/index.js'
import { AppHeader } from '../AppHeader/index.js'
import { useToast } from '../Toast/index.js'
import { SwitchInput } from '../SwitchInput/index.js'

export const KitchenSink = () => {
  const [enabled, setEnabled] = useState(true)
  const [notesEnabled, setNotesEnabled] = useState(false)
  return (
    <Form
      disabled={!enabled}
      validate={() => {
        const errors: FormErrors = {}

        errors['text'] = 'text error'
        errors['textarea'] = 'textarea error'
        errors['switch'] = 'switch error'
        errors['checkbox'] = 'checkbox error'
        errors['number'] = 'number error'
        errors['date'] = 'date error'
        errors['datetime'] = 'datetime error'
        errors['select'] = 'select error'
        errors['richtext'] = 'richtext error'
        errors['reference'] = 'reference error'
        errors['tag'] = 'tag error'

        return errors
      }}
      groups={[
        {
          label: 'Test group 1',
          description: 'This a group description',
          fields: ['switch', 'reference', 'date'],
        },
        {
          label: 'Test group 2',
          description: 'This a group description',
          fields: ['number', 'textarea'],
        },
      ]}
      fields={{
        text: {
          type: 'text',
          label: 'text',
          description: 'text desc',
          placeholder: 'text placeholder',
          note: notesEnabled
            ? { title: 'note title', description: 'note description' }
            : null,
        },
        textarea: {
          type: 'textarea',
          label: 'textarea',
          description: 'textarea desc',
          placeholder: 'textarea placeholder',
          note: notesEnabled
            ? { title: 'note title', description: 'note description' }
            : null,
        },
        switch: {
          type: 'switch',
          label: 'switch',
          description: 'switch desc',
          placeholder: 'switch placeholder',
          note: notesEnabled
            ? { title: 'note title', description: 'note description' }
            : null,
        },
        checkbox: {
          type: 'checkbox',
          label: 'checkbox',
          description: 'checkbox desc',
          placeholder: 'checkbox placeholder',
          note: notesEnabled
            ? { title: 'note title', description: 'note description' }
            : null,
        },
        number: {
          type: 'number',
          label: 'number',
          description: 'number desc',
          placeholder: 'number placeholder',
          note: notesEnabled
            ? { title: 'note title', description: 'note description' }
            : null,
        },
        date: {
          type: 'date',
          label: 'date',
          description: 'date desc',
          placeholder: 'date placeholder',
          note: notesEnabled
            ? { title: 'note title', description: 'note description' }
            : null,
        },
        datetime: {
          type: 'datetime',
          label: 'datetime',
          description: 'datetime desc',
          placeholder: 'datetime placeholder',
          note: notesEnabled
            ? { title: 'note title', description: 'note description' }
            : null,
        },
        select: {
          type: 'select',
          label: 'select',
          description: 'select desc',
          placeholder: 'select placeholder',
          note: notesEnabled
            ? { title: 'note title', description: 'note description' }
            : null,
          options: [
            { value: 'value1', label: 'label1' },
            { value: 'value2', label: 'label2' },
          ],
          filterable: true,
        },
        richtext: {
          type: 'richtext',
          label: 'richtext',
          description: 'richtext desc',
          placeholder: 'richtext placeholder',
          note: notesEnabled
            ? { title: 'note title', description: 'note description' }
            : null,
        },
        reference: {
          type: 'reference',
          label: 'reference',
          description: 'reference desc',
          placeholder: 'reference placeholder',
          placeholderIcon: 'reference',
          note: notesEnabled
            ? { title: 'note title', description: 'note description' }
            : null,
          ref: 'author',
          variant: 'single',
        },
        tag: {
          type: 'tag',
          label: 'tag',
          description: 'tag desc',
          placeholder: 'tag placeholder',
          placeholderIcon: 'id',
          note: notesEnabled
            ? { title: 'note title', description: 'note description' }
            : null,
          variant: 'string',
        },
      }}
      onSubmit={console.log}
      endpoints={{
        query: 'get-demo-data',
        schema: 'get-demo-schema',
        totalQuery: 'get-demo-total',
      }}
    >
      {({ submitForm, validateForm }) => (
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            gap: 24,
            width: '100%',
            maxWidth: 700,
            margin: '0 auto',
            padding: '64px 0',
          }}
        >
          <div style={{ display: 'flex', gap: 12 }}>
            <SwitchInput
              value={enabled}
              onChange={setEnabled}
              description={enabled ? 'Fields enabled' : 'Fields disabled'}
            />
            <SwitchInput
              value={notesEnabled}
              onChange={setNotesEnabled}
              description={notesEnabled ? 'Notes shown' : 'Notes hidden'}
            />
            <div style={{ display: 'flex', gap: 12, marginLeft: 'auto' }}>
              <Button
                variant="border"
                onClick={() => {
                  validateForm()
                }}
              >
                Validate
              </Button>

              <Button
                onClick={() => {
                  submitForm()
                }}
              >
                Submit
              </Button>
            </div>
          </div>
          <Form.Tabs />
          <Form.Fields />
        </div>
      )}
    </Form>
  )
}

export const Nested = () => {
  return (
    <Form
      fields={{
        foo: { type: 'text', label: 'Foo' },
        bar: { type: 'number', label: 'Bar' },
        nested: {
          foo: { type: 'text', label: 'Foo' },
          bar: { type: 'number', label: 'Bar' },
          deeperNested: {
            foo: { type: 'text', label: 'Foo' },
            bar: { type: 'number', label: 'Bar' },
            thirdNesting: {
              fourthNesting: {
                foo: { type: 'text', label: 'Foo' },
                bar: { type: 'number', label: 'Bar' },
              },
            },
          },
        },
      }}
      onSubmit={console.log}
    >
      {({ submitForm }) => (
        <div
          style={{
            width: 500,
            display: 'flex',
            gap: 24,
          }}
        >
          <Form.Fields />
          <Button
            onClick={() => {
              submitForm()
            }}
          >
            Submit
          </Button>
        </div>
      )}
    </Form>
  )
}

export const Component = () => {
  return (
    <Form
      fields={{
        text: { type: 'text', label: 'Text', description: 'this is a desc' },
        textarea: { type: 'textarea', label: 'Textarea' },
        number: { type: 'number', label: 'Number' },
        simpleSelect: {
          type: 'select',
          label: 'Simple select',
          options: [
            { value: 'option1', label: 'Option 1' },
            { value: 'option2', label: 'Option 2' },
            { value: 'option3', label: 'Option 3' },
          ],
        },
        fancySelect: {
          type: 'select',
          label: 'Fancy select',
          options: [
            {
              value: 'live',
              label: (
                <Badge color="green-subtle" leadIcon="settings">
                  Live
                </Badge>
              ),
              labelFilterText: 'Live',
            },
            {
              value: 'scheduled',
              label: (
                <Badge color="blue-subtle" leadIcon="date">
                  Scheduled
                </Badge>
              ),
              labelFilterText: 'Scheduled',
            },
          ],
        },
        switch: { type: 'switch', label: 'Switch' },
        checkbox: { type: 'checkbox', label: 'Checkbox' },
        date: { type: 'datetime', label: 'Date' },
        datetime: { type: 'datetime', label: 'DateTime' },
      }}
      validate={(values) => {
        const errors: FormErrors = {}

        if (!values['text']) {
          errors['text'] = 'text is required'
        }

        if (!values['checkbox']) {
          errors['checkbox'] = 'checkbox is required'
        }

        if (!values['datetime']) {
          errors['datetime'] = 'datetime is required'
        } else if ((values['datetime'] as number) < Date.now()) {
          errors['datetime'] = 'datetime must be in the future'
        }

        return errors
      }}
      onSubmit={console.log}
    >
      {({
        submitForm,
        resetForm,
        validateForm,
        isSubmitting,
        isValidating,
        isDirty,
      }) => (
        <>
          <Form.Fields />
          <div
            style={{
              display: 'flex',
              gap: 16,
              paddingTop: 16,
            }}
          >
            <Button disabled={isSubmitting} onClick={resetForm} variant="ghost">
              Reset
            </Button>
            <Button
              disabled={isSubmitting}
              loading={isValidating}
              onClick={() => {
                validateForm()
              }}
              variant="border"
            >
              Validate
            </Button>
            <div style={{ marginLeft: 'auto' }}>
              <Button
                disabled={isSubmitting || !isDirty}
                loading={isSubmitting}
                onClick={() => {
                  submitForm()
                }}
              >
                Submit
              </Button>
            </div>
          </div>
        </>
      )}
    </Form>
  )
}

export const FullScreenGroups = () => {
  const toast = useToast()

  return (
    <Form
      groups={[
        {
          label: 'General',
          description: 'Tile, type and platforms',
          fields: ['title', 'type', 'platform', 'price'],
        },
        {
          label: 'Winners and prizes',
          description: 'Number of winners, prize category',
          fields: ['foo', 'foo2', 'bar', 'bar2'],
        },
        {
          label: 'Legal',
          description: 'Terms & conditions, privacy policy',
          fields: ['terms', 'privacy'],
        },
      ]}
      fields={(values) => ({
        title: {
          type: 'text',
          label: 'Title',
          description: 'Used internally and publicly',
        },
        body: {
          type: 'richtext',
          label: 'Body',
        },
        type: {
          type: 'select',
          label: 'Type',
          options: [
            { label: 'Cashcall', value: 'cashcall' },
            { label: 'SMS', value: 'sms' },
          ],
          note:
            values.type === 'sms'
              ? {
                  title: 'What are SMS games?',
                  description: 'Lorem ipsum',
                }
              : {
                  title: 'What are cashcall games?',
                  description:
                    'In cashcall games the participant calls or texts a phone number. Based on a set of rules they have the chance to win awards.',
                },
        },
        platform: {
          type: 'select',
          label: 'Platform',
          options: [
            { label: 'Bild', value: 'bild' },
            { label: 'Bild+', value: 'bildplus' },
          ],
        },
        price: {
          type: 'number',
          label: 'Price (EUR)',
        },
        // referenceUser: {
        //   label: 'User',
        //   type: 'references',
        //   referencesType: 'user',
        // },
        foo: {
          type: 'text',
          label: 'Foo',
        },
        foo2: {
          type: 'checkbox',
          label: 'Foo 2',
          description:
            'As you can see here, text breaks into new lines without any truncation.',
        },
        bar: {
          type: 'switch',
          label: 'Bar',
          description:
            'As you can see here, text breaks into new lines without any truncation.',
        },
        bar2: {
          type: 'datetime',
          label: 'Bar 2',
          variant: 'date-time',
        },
        terms: {
          type: 'textarea',
          label: 'Terms & Conditions',
        },
        privacy: {
          type: 'textarea',
          label: 'Privacy policy',
        },
      })}
      validate={(values) => {
        const errors: FormErrors = {}

        if (!values.title) {
          errors.title = 'A title is required'
        }

        return errors
      }}
      onSubmitError={() => {
        toast("Couldn't save changes", {
          icon: 'error',
          description: 'Make sure all fields are valid before proceeding',
        })
      }}
      onSubmit={() => {}}
    >
      {({ submitForm }) => (
        <div style={{ display: 'flex' }}>
          <div style={{ height: '100svh' }}>
            <Sidebar value="games" onChange={console.log}>
              <Sidebar.Header>
                <svg fill="none" viewBox="0 0 80 80" width="40" height="40">
                  <path
                    d="m60.822 26.3984-19.0829 19.0829h-19.0829l19.0829-19.0829z"
                    fill="#4b41ff"
                  ></path>
                  <path
                    d="m65.3125 45.481-19.0829 19.0828h-23.5734l19.0829-19.0828z"
                    fill="#ff1f85"
                  ></path>
                  <path
                    d="m41.7391 8.4375-19.0829 19.0829v17.9606l19.0829-19.0829z"
                    fill="#008cff"
                  ></path>
                </svg>
              </Sidebar.Header>
              <Sidebar.Items>
                <Sidebar.Group title="Content management">
                  <Sidebar.Item value="games" icon="columns">
                    Games
                  </Sidebar.Item>
                </Sidebar.Group>
              </Sidebar.Items>
            </Sidebar>
          </div>
          <div
            style={{
              width: '100%',
              height: '100svh',
              display: 'flex',
              flexDirection: 'column',
            }}
          >
            <AppHeader>
              <AppHeader.Title>Create Game</AppHeader.Title>
              <AppHeader.Right>
                <Button
                  onClick={() => {
                    submitForm()
                  }}
                >
                  Save changes
                </Button>
              </AppHeader.Right>
            </AppHeader>
            <div
              style={{
                display: 'flex',
                height: `calc(100vh - 68px)`,
                overflowY: 'auto',
              }}
            >
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  gap: 32,
                  maxWidth: 720,
                  width: '100%',
                  margin: '32px auto 0',
                }}
              >
                <Form.Tabs />
                <Form.Fields />
                <div style={{ height: 1, width: '100%', flexShrink: 0 }} />
              </div>
            </div>
          </div>
        </div>
      )}
    </Form>
  )
}

export const Async = () => {
  const [data, setData] = useState<any>()

  useEffect(() => {
    setInterval(() => {
      setData((p: any) => ({
        ...p,
        async: crypto.randomUUID(),
        rich: `{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"${crypto.randomUUID()}","type":"text","version":1}],"direction":"ltr","format":"","indent":0,"type":"paragraph","version":1,"textFormat":0,"textStyle":""}],"direction":"ltr","format":"","indent":0,"type":"root","version":1}}`,
      }))
    }, 1000)
  }, [])

  return (
    <Form
      initialValues={data}
      fields={{
        normal: { type: 'text', label: 'Normal' },
        async: { type: 'text', label: 'AsyncDynamicValue' },
        rich: { type: 'richtext', label: 'Test' },
      }}
      validate={async () => {
        await new Promise((resolve) => {
          setTimeout(() => {
            resolve('foo')
          }, 1000)
        })

        return {}
      }}
      onSubmit={async () => {
        await new Promise((resolve) => {
          setTimeout(() => {
            resolve('foo')
          }, 2000)
        })
      }}
    >
      {({
        submitForm,
        resetForm,
        validateForm,
        isSubmitting,
        isValidating,
        isDirty,
      }) => (
        <>
          <Form.Fields />
          <div
            style={{
              display: 'flex',
              gap: 16,
              paddingTop: 16,
            }}
          >
            <Button disabled={isSubmitting} onClick={resetForm} variant="ghost">
              Reset
            </Button>
            <Button
              disabled={isSubmitting}
              loading={isValidating}
              onClick={() => {
                validateForm()
              }}
              variant="border"
            >
              Validate
            </Button>
            <div style={{ marginLeft: 'auto' }}>
              <Button
                disabled={isSubmitting || !isDirty}
                loading={isSubmitting}
                onClick={() => {
                  submitForm()
                }}
              >
                Submit
              </Button>
            </div>
          </div>
        </>
      )}
    </Form>
  )
}
