import { useState } from 'react';
import { FormProvider, useForm } from 'react-hook-form';

import { Button, Stack, Typography } from '@mui/material';
import { type Meta, type StoryObj } from '@storybook/react-vite';
import { IconSearch } from '@tabler/icons-react';

import FormInputClassic from './form';
import { type InputProps } from './types';
import InputClassic from '.';

const meta: Meta<typeof InputClassic> = {
  component: InputClassic,
  title: 'Design System/Inputs/Classic',
  tags: ['autodocs'],
  argTypes: {
    label: { control: 'text' },
    placeholder: { control: 'text' },
    helperText: { control: 'text' },
    errorText: { control: 'text' },
    labelTooltip: { control: 'text' },
    error: { control: 'boolean' },
    success: { control: 'boolean' },
    disabled: { control: 'boolean' },
    fullWidth: { control: 'boolean' },
    hasCounter: { control: 'boolean' },
    hasHelperBullet: { control: 'boolean' },
    hideErrorText: { control: 'boolean' },
    showClear: { control: 'boolean' },
    startAdormentPosition: {
      control: 'radio',
      options: ['start', 'center', 'end'],
    },
    startAdornment: { control: false },
    transform: { control: false },
    onKeyDown: { control: false },
    onBlur: { control: false },
    slotProps: { control: false },
    sx: { control: false },
  },
  args: {
    value: 'value!',
  },
};

export default meta;

type Story = StoryObj<InputProps>;

export const NoLabel: Story = {
  args: {
    placeholder: 'Placeholder',
  },
};

export const DefaultWithHelper: Story = {
  args: {
    placeholder: 'Placeholder',
    label: 'Label',
    helperText: 'Helper',
  },
};

export const InputSmall: Story = {
  args: {
    placeholder: 'Placeholder',
    size: 'small',
  },
};

export const Error: Story = {
  args: {
    placeholder: 'Placeholder',
    label: 'Label',
    helperText: 'Helper text',
    errorText: 'Error text',
    value: 'value!',
    error: true,
  },
};

export const LongError: Story = {
  args: {
    placeholder: 'Placeholder',
    label: 'Label',
    helperText: 'Helper text',
    errorText: 'Long error text to test styles',
    value: 'value!',
    error: true,
    fullWidth: false,
    sx: { width: '200px' },
  },
};

export const ErrorNoHelperText: Story = {
  args: {
    placeholder: 'Placeholder',
    label: 'Label',
    hideErrorText: true,
    errorText: 'Error text',
    value: 'value!',
    error: true,
    fullWidth: false,
    sx: { width: '200px' },
  },
};

export const Success: Story = {
  args: {
    placeholder: 'Placeholder',
    label: 'Label',
    helperText: 'Helper text',
    errorText: 'Error text',
    value: 'value!',
    success: true,
  },
};

export const Disabled: Story = {
  args: {
    placeholder: 'Placeholder',
    label: 'Label',
    helperText: 'Helper text',
    errorText: 'Error text',
    value: 'value!',
    disabled: true,
  },
};

export const WithBullet: Story = {
  args: {
    placeholder: 'Placeholder',
    label: 'Label',
    helperText: 'Rule helper text',
    hasHelperBullet: true,
  },
};

export const WithLabelTooltip: Story = {
  args: {
    placeholder: 'Placeholder',
    label: 'Label',
    labelTooltip: 'This is a tooltip for the label',
    slotProps: {
      labelTooltip: {
        placement: 'top',
        arrow: true,
      },
    },
  },
};

export const FormInputClassicStory: Story = {
  args: {
    placeholder: 'Placeholder',
    label: 'Label',
    helperText: 'Helper text',
    errorText: 'Error text',
    value: 'value!',
    disabled: false,
    error: false,
  },
  render: args => {
    const form = useForm({
      defaultValues: {
        myInput: '',
      },
      mode: 'onChange',
    });
    return (
      <FormProvider {...form}>
        <FormInputClassic
          inputProps={{
            placeholder: args.placeholder,
            label: args.label,
            helperText: args.helperText,
            hasCounter: args.hasCounter,
            errorText: args.errorText,
            disabled: args.disabled,
            autoComplete: 'email',
            type: 'email',
          }}
          rules={{ required: true }}
          name="myInput"
        />
      </FormProvider>
    );
  },
};

export const FormInputClassicErrorStory: Story = {
  render: () => {
    const form = useForm({
      defaultValues: {
        myInput: '',
      },
    });
    return (
      <FormProvider {...form}>
        <FormInputClassic
          inputProps={{
            placeholder: 'Placeholder',
            label: 'Label',
            helperText: 'Helper text',
            error: true,
            errorText: 'Custom error message',
          }}
          name="myInput"
        />
      </FormProvider>
    );
  },
};

export const FormInputSmallStory: Story = {
  args: {
    placeholder: 'Placeholder',
    label: 'Label',
    helperText: 'Helper text',
    errorText: 'Error text',
    value: 'value!',
    disabled: false,
    error: false,
    size: 'small',
  },
  render: args => {
    const form = useForm({
      defaultValues: {
        myInput: '',
      },
      mode: 'onChange',
    });
    return (
      <FormProvider {...form}>
        <FormInputClassic
          inputProps={{
            placeholder: args.placeholder,
            label: args.label,
            helperText: args.helperText,
            hasCounter: args.hasCounter,
            errorText: args.errorText,
            disabled: args.disabled,
            size: args.size,
          }}
          rules={{ required: true }}
          name="myInput"
        />
      </FormProvider>
    );
  },
};

export const FormInputClassicMultilineStory: Story = {
  render: () => {
    const form = useForm({
      defaultValues: {
        myInput: '',
      },
    });
    return (
      <FormProvider {...form}>
        <FormInputClassic
          inputProps={{
            placeholder: 'Placeholder',
            label: 'Label',
            helperText: 'Helper text',
            hasCounter: true,
            multiline: true,
          }}
          name="myInput"
        />
      </FormProvider>
    );
  },
};

export const FormInputClassicWithStartAdorment: Story = {
  render: () => {
    const form = useForm({
      defaultValues: {
        myInput: '',
      },
    });
    return (
      <FormProvider {...form}>
        <FormInputClassic
          inputProps={{
            placeholder: 'Placeholder',
            label: 'Label',
            helperText: 'Helper text',
            startAdornment: <IconSearch />,
          }}
          name="myInput"
        />
      </FormProvider>
    );
  },
};

export const FormInputClassicWithStartAdormentMultiline: Story = {
  render: () => {
    const form = useForm({
      defaultValues: {
        myInput: '',
      },
    });
    return (
      <FormProvider {...form}>
        <FormInputClassic
          inputProps={{
            placeholder: 'Placeholder',
            label: 'Label',
            helperText: 'Helper text',
            multiline: true,
            showClear: false,
            minRows: 1,
            maxRows: 5,
            startAdormentPosition: 'end',
            startAdornment: <IconSearch />,
          }}
          name="myInput"
        />
      </FormProvider>
    );
  },
};

export const FormInputClassicWithMask: Story = {
  render: () => {
    const form = useForm({
      defaultValues: {
        unmaskedInput: '',
      },
    });
    const { watch } = form;
    return (
      <Stack sx={{ gap: 2 }}>
        <FormProvider {...form}>
          <FormInputClassic
            inputProps={{
              maxLength: 12,
              transform: {
                input: value => value.replace(/\s/g, ''),
                output: value => {
                  // Strip spaces first to avoid taking them as input
                  const stripped = value.replace(/\s/g, '');
                  return stripped.replace(/(.{4})(?=.)/g, '$1 ');
                },
              },
            }}
            name="unmaskedInput"
          />
        </FormProvider>
        <pre>{JSON.stringify(watch(), null, 2)}</pre>
      </Stack>
    );
  },
};

export const FormInputRename: Story = {
  args: {
    placeholder: 'Placeholder',
    size: 'small',
    hasCounter: false,
  },
  render: args => {
    const [rename, setRename] = useState(false);
    const form = useForm({
      defaultValues: {
        name: args.value || '',
      },
      mode: 'onChange',
    });

    const handleSave = () => {
      setRename(false);
      form.setValue('name', form.getValues('name'));
    };

    return (
      <>
        {rename && (
          <FormProvider {...form}>
            <Stack
              sx={{
                alignItems: 'left',
                gap: 2,
              }}
            >
              <FormInputClassic
                inputProps={{
                  placeholder: args.placeholder,
                  label: args.label,
                  helperText: args.helperText,
                  hasCounter: args.hasCounter,
                  errorText: args.errorText,
                  disabled: args.disabled,
                  size: args.size,
                  onKeyDown: e => e.key === 'Enter' && handleSave(),
                  onBlur: handleSave,
                  autoFocus: true,
                  sx: { width: '20%', px: 'auto' },
                }}
                rules={{ required: true }}
                name="name"
              />
              <Button
                disabled
                variant="primary"
                size="medium"
                sx={{ width: '20%', px: 'auto' }}
              >
                Rename
              </Button>
            </Stack>
          </FormProvider>
        )}
        {!rename && (
          <Stack
            sx={{
              alignItems: 'left',
              gap: 2,
            }}
          >
            <Typography variant="globalM">{form.watch('name')}</Typography>
            <Button
              onClick={() => setRename(true)}
              variant="primary"
              size="medium"
              sx={{ width: '20%', px: 'auto' }}
            >
              Rename
            </Button>
          </Stack>
        )}
      </>
    );
  },
};
