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

import { Stack, Typography } from '@mui/material';
import { type IconInterface } from '@src/types/icons';
import { type Meta, type StoryObj } from '@storybook/react-vite';

import FormIconPicker from './form';
import {
  DEFAULT_VALUE,
  DEMO_OPTIONS,
  DEMO_TEXT,
  EMOJI_DEFAULT_VALUE,
  SPANISH_TEXT,
} from './mocks';
import { IconPickerTab } from './types';
import IconPicker from '.';

const meta: Meta<typeof IconPicker> = {
  component: IconPicker,
  title: 'Composed Components/IconPicker',
  tags: ['autodocs'],
  parameters: {
    docs: {
      description: {
        component:
          'A controlled picker that lets the user select an image icon or emoji. Supports custom image grids, emoji browsing, and optional file upload with built-in cropping.',
      },
    },
  },
  argTypes: {
    value: {
      description: 'Currently selected icon (`IconInterface | null`).',
      control: false,
    },
    onChange: {
      description: 'Callback fired when the selection changes.',
      action: 'onChange',
    },
    imageOptions: {
      description: 'Array of `ImageIconOption` objects for the images tab.',
      control: false,
    },
    onUpload: {
      description:
        'Optional callback receiving the cropped `File` after the user uploads a custom icon.',
      action: 'onUpload',
    },
    text: {
      description:
        'Translated strings for tabs and cropping modal (required, provided by host app).',
      control: 'object',
    },
    tabs: {
      description: 'Which tabs to show. Defaults to `["icons", "emojis"]`.',
      options: [
        [IconPickerTab.ICONS, IconPickerTab.EMOJIS],
        [IconPickerTab.ICONS],
        [IconPickerTab.EMOJIS],
      ],
      control: { type: 'select' },
    },
    disabled: {
      description: 'Disables the trigger button.',
      control: 'boolean',
    },
    sx: {
      description: 'Styles applied to the trigger button root element.',
      control: false,
    },
    slotProps: {
      description: 'Props forwarded to internal subcomponents (menu).',
      control: false,
    },
  },
  args: {
    imageOptions: DEMO_OPTIONS,
    text: DEMO_TEXT,
    disabled: false,
  },
};

export default meta;

type Story = StoryObj<typeof IconPicker>;

export const Default: Story = {
  render: args => {
    const [value, setValue] = useState<IconInterface | null>(DEFAULT_VALUE);

    return (
      <Stack sx={{ gap: 2 }}>
        <IconPicker
          {...args}
          value={value}
          onChange={icon => {
            setValue(icon);
            args.onChange?.(icon);
          }}
        />
        <Typography variant="globalXS">
          Selected: {value?.type} — {value?.value?.slice(0, 50)}
        </Typography>
      </Stack>
    );
  },
};

export const EmojisOnly: Story = {
  render: args => {
    const [value, setValue] = useState<IconInterface | null>(
      EMOJI_DEFAULT_VALUE,
    );

    return (
      <IconPicker
        {...args}
        tabs={[IconPickerTab.EMOJIS]}
        value={value}
        onChange={icon => {
          setValue(icon);
          args.onChange?.(icon);
        }}
      />
    );
  },
};

export const ImagesOnly: Story = {
  render: args => {
    const [value, setValue] = useState<IconInterface | null>(DEFAULT_VALUE);

    return (
      <IconPicker
        {...args}
        tabs={[IconPickerTab.ICONS]}
        value={value}
        onChange={icon => {
          setValue(icon);
          args.onChange?.(icon);
        }}
        onUpload={file => {
          console.log('Uploaded file:', file.name);
          args.onUpload?.(file);
        }}
      />
    );
  },
};

export const Disabled: Story = {
  render: args => (
    <IconPicker
      {...args}
      value={DEFAULT_VALUE}
      onChange={() => console.debug('[IconPicker] Disabled | onChange')}
      disabled
    />
  ),
};

export const SpanishText: Story = {
  render: args => {
    const [value, setValue] = useState<IconInterface | null>(DEFAULT_VALUE);

    return (
      <IconPicker
        {...args}
        value={value}
        onChange={setValue}
        text={SPANISH_TEXT}
        onUpload={file => console.log('Upload:', file.name)}
      />
    );
  },
};

export const WithForm: Story = {
  render: args => {
    const form = useForm<{ icon: IconInterface }>({
      defaultValues: { icon: DEFAULT_VALUE },
    });

    return (
      <FormProvider {...form}>
        <Stack sx={{ gap: 2 }}>
          <FormIconPicker
            name="icon"
            inputProps={{
              text: DEMO_TEXT,
              imageOptions: args.imageOptions,
              onUpload: file => console.log('Upload:', file.name),
            }}
          />
          <Typography variant="globalXS">
            Form value: {JSON.stringify(form.watch('icon'))}
          </Typography>
        </Stack>
      </FormProvider>
    );
  },
};
