import type { Meta, StoryObj } from '@storybook/react'
import React from 'react'
import { SvgCoinsStack } from '@chainlink/blocks-icons'
import { Tag } from '../Tag'
import {
  FieldInputRoot,
  FieldInputIcon,
  FieldInputControl,
  FieldInputAction,
} from './FieldInput'

const meta = {
  title: 'Form/Input/FieldInput/Primitives',
  component: FieldInputRoot,
  parameters: {
    layout: 'centered',
  },
} satisfies Meta<typeof FieldInputRoot>

export default meta
type Story = StoryObj<typeof meta>

export const Default: Story = {
  render: (_args) => {
    return (
      <FieldInputRoot>
        <FieldInputIcon>
          <SvgCoinsStack />
        </FieldInputIcon>
        <FieldInputControl placeholder="Enter amount" />
        <FieldInputAction />
      </FieldInputRoot>
    )
  },
}

export const WithMaxButton: Story = {
  render: (_args) => {
    return (
      <form>
        <FieldInputRoot type="number" name="amount">
          <FieldInputIcon>
            <SvgCoinsStack />
          </FieldInputIcon>
          <FieldInputControl placeholder="Enter amount" />
          <FieldInputAction>
            <Tag
              variant="muted"
              size="sm"
              className="cursor-pointer"
              onClick={(e) => {
                const input = e.currentTarget
                  .closest('form')
                  ?.querySelector('input')
                if (input) {
                  input.value = '10000'
                }
              }}
            >
              Max
            </Tag>
          </FieldInputAction>
        </FieldInputRoot>
      </form>
    )
  },
}

const WithMaxButtonAndInvalidStateComponent = () => {
  const [value, setValue] = React.useState('50000')
  const maxValue = '1000'
  const error =
    parseFloat(value) > parseFloat(maxValue)
      ? `Amount cannot exceed ${maxValue}`
      : undefined

  return (
    <FieldInputRoot
      type="number"
      error={error}
      value={value}
      onChange={(e) => setValue(e.target.value)}
    >
      <FieldInputIcon>
        <SvgCoinsStack />
      </FieldInputIcon>
      <FieldInputControl placeholder="Enter amount" />
      <FieldInputAction isInvalid={!!error}>
        <Tag
          variant="muted"
          size="sm"
          className="cursor-pointer"
          onClick={() => setValue(maxValue)}
        >
          Max
        </Tag>
      </FieldInputAction>
    </FieldInputRoot>
  )
}

export const WithMaxButtonAndInvalidState: Story = {
  render: () => <WithMaxButtonAndInvalidStateComponent />,
}
