import {
  Badge,
  BasedFinder,
  Button,
  Form,
  IconButton,
  Modal,
  capitalize,
  colors,
  useToast,
} from '@based/ui'
import { useState } from 'react'

export const meta: Based.UI.Extractor.MetaDescriptor = {
  name: 'Modal',
  group: 'Overlays',
  section: 'components',
  icon: 'edit',
  component: Modal,
  subtitle:
    'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
  showApi: true,
  showUsage: true,
}

export const blocks: Based.UI.Extractor.BlocksDescriptor[] = [
  {
    name: 'Small',
    type: 'component',
    description: 'Small modal with a header, body, and actions.',
    style: {
      size: 'small',
      frame: false,
      flex: {
        justifyContent: 'center',
        alignItems: 'center',
      },
    },
    render: () => {
      const [isModalOpen, setIsModalOpen] = useState(false)
      const options = ['neutral', 'red', 'orange', 'green'].map(
        (color, index) => {
          return {
            label: (
              <Badge color={`${color}-subtle` as any}>
                {capitalize(color)}
              </Badge>
            ),
            value: index,
          }
        },
      )

      return (
        <>
          <Button variant="border" onClick={() => setIsModalOpen(true)}>
            Open Modal
          </Button>
          <Modal open={isModalOpen} onOpenChange={() => {}} size="small">
            <Modal.Header
              title="Create new tag"
              description="Your tag will be visible to everyone in the workspace."
            />
            <Modal.Body>
              <Form
                fields={{
                  label: { type: 'text', label: 'Label' },
                  style: {
                    type: 'select',
                    label: 'Style',
                    options,
                  },
                }}
                onSubmit={console.log}
              >
                {() => <Form.Fields />}
              </Form>
            </Modal.Body>
            <Modal.Actions>
              <Button
                onClick={() => {
                  setIsModalOpen(false)
                }}
                variant="border"
              >
                Cancel
              </Button>
              <Button
                onClick={() => {
                  setIsModalOpen(false)
                }}
              >
                Create tag
              </Button>
            </Modal.Actions>
          </Modal>
        </>
      )
    },
  },
  {
    name: 'Regular',
    type: 'component',
    description: 'Regular modal with scrollable body content.',
    style: {
      size: 'small',
      frame: false,
      flex: {
        justifyContent: 'center',
        alignItems: 'center',
      },
    },
    render: () => {
      const [isModalOpen, setIsModalOpen] = useState(false)

      return (
        <>
          <Button variant="border" onClick={() => setIsModalOpen(true)}>
            Open Modal
          </Button>
          <Modal open={isModalOpen} onOpenChange={() => {}} size="regular">
            <Modal.Header title="Edit author" />
            <Modal.Body>
              <Form
                fields={{
                  name: { type: 'text', label: 'Name' },
                  address: { type: 'text', label: 'Address' },
                  country: {
                    type: 'select',
                    label: 'Country',
                    options: [
                      {
                        value: 'nl',
                        label: 'Netherlands',
                      },
                      {
                        value: 'br',
                        label: 'Brazil',
                      },
                      {
                        value: 'pt',
                        label: 'Portugal',
                      },
                      {
                        value: 'it',
                        label: 'Italy',
                      },
                      {
                        value: 'fl',
                        label: 'Finland',
                      },
                      {
                        value: 'hu',
                        label: 'Hungary',
                      },
                      {
                        value: 'ch',
                        label: 'China',
                      },
                      {
                        value: 'fr',
                        label: 'France',
                      },
                      {
                        value: 'ge',
                        label: 'Germany',
                      },
                      {
                        value: 'sw',
                        label: 'Switzerland',
                      },
                    ],
                  },
                  socialMedia: { type: 'text', label: 'Social media' },
                  shortBio: {
                    type: 'textarea',
                    label: 'Short bio',
                  },
                  about: {
                    type: 'textarea',
                    label: 'About',
                  },
                  active: { type: 'switch', label: 'Active' },
                  birthday: { type: 'datetime', label: 'Date of birth' },
                  role: {
                    type: 'select',
                    label: 'Role',
                    options: [
                      {
                        value: 'editor',
                        label: <Badge color="orange-subtle">Editor</Badge>,
                      },
                      {
                        value: 'writer',
                        label: <Badge color="green-subtle">Writer</Badge>,
                      },
                      {
                        value: 'director',
                        label: <Badge color="blue-subtle">Director</Badge>,
                      },
                    ],
                  },
                }}
                onSubmit={console.log}
              >
                {() => <Form.Fields />}
              </Form>
            </Modal.Body>
            <Modal.Actions>
              <Button onClick={() => setIsModalOpen(false)} variant="border">
                Cancel
              </Button>
              <Button onClick={() => setIsModalOpen(false)}>
                Save changes
              </Button>
            </Modal.Actions>
          </Modal>
        </>
      )
    },
  },
  {
    name: 'Large',
    type: 'component',
    description: 'Large modal with body content and actions.',
    style: {
      size: 'small',
      frame: false,
      flex: {
        justifyContent: 'center',
        alignItems: 'center',
      },
    },
    render: () => {
      const [isModalOpen, setIsModalOpen] = useState(false)
      const toast = useToast()

      return (
        <>
          <Button variant="border" onClick={() => setIsModalOpen(true)}>
            Open Modal
          </Button>
          <Modal open={isModalOpen} onOpenChange={() => {}} size="large">
            <BasedFinder
              endpoints={{
                query: 'get-data',
                schema: 'get-schema',
                totalQuery: 'get-total',
              }}
              type="user"
              transformFields={(fields) => {
                fields.timestamp.calendar = { type: 'start' }
                delete fields.start
                delete fields.end

                return fields
              }}
              itemActions={[
                {
                  label: 'Delete',
                  color: 'red',
                  icon: 'delete',
                  onClick: (item) => toast(`delete ${item.id}`),
                },
              ]}
              bulkActions={[
                {
                  label: 'Delete',
                  color: 'red',
                  icon: 'delete',
                  onClick: (selected) => toast(`delete ${selected.length}`),
                },
              ]}
            >
              {({ view }) => (
                <>
                  <Modal.Header>
                    <BasedFinder.Header
                      title="Select articles"
                      trailButton={
                        <IconButton
                          icon="close"
                          onClick={() => setIsModalOpen(false)}
                        />
                      }
                    />
                  </Modal.Header>
                  <Modal.Body>
                    <div
                      style={{
                        height: 'calc(100svh - 2*24px - 2*84px)',
                        borderRadius: 16,
                        ...(view !== 'calendar' && {
                          border: `1px solid ${colors.neutral20Adjusted}`,
                          overflow: 'hidden',
                        }),
                      }}
                    >
                      <BasedFinder.Body
                        tableHeaderTransparentBackground={false}
                        calendarPadding={false}
                      />
                    </div>
                  </Modal.Body>
                  <Modal.Actions>
                    {() => (
                      <>
                        <Button
                          keyHint="Esc"
                          variant="border"
                          onClick={() => setIsModalOpen(false)}
                        >
                          Cancel
                        </Button>
                        <Button
                          keyHint="Enter"
                          onClick={async () => {
                            await new Promise((resolve) => {
                              setTimeout(() => {
                                resolve('')
                              }, 2000)
                            })
                            setIsModalOpen(false)
                          }}
                        >
                          Save
                        </Button>
                      </>
                    )}
                  </Modal.Actions>
                </>
              )}
            </BasedFinder>
          </Modal>
        </>
      )
    },
  },
]
