import { useEffect, useRef, useState } from 'react';

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

import useDimensions from '.';

const meta: Meta = {
  title: 'Hooks/useDimensions',
  tags: ['autodocs'],
  parameters: {
    docs: {
      description: {
        component:
          'Hook that observes an element and returns its width and height. Use the returned ref and attach it to the element to measure, or pass an element directly.',
      },
    },
  },
};

export default meta;

type Story = StoryObj<typeof meta>;

const DimensionsDisplay = () => {
  const { ref, dimensions } = useDimensions();

  return (
    <Stack sx={{ gap: 2 }}>
      <Typography variant="globalS">
        Resize the box below to see dimensions update.
      </Typography>
      <Box
        ref={ref}
        sx={{
          width: '100%',
          minHeight: 200,
          maxWidth: 400,
          resize: 'both',
          overflow: 'auto',
          border: '1px dashed',
          borderColor: 'divider',
          borderRadius: 1,
          p: 2,
          bgcolor: 'action.hover',
        }}
      >
        <Typography variant="body2">
          width: {dimensions.width}px · height: {dimensions.height}px
        </Typography>
      </Box>
    </Stack>
  );
};

export const WithRef: Story = {
  render: () => <DimensionsDisplay />,
  parameters: {
    docs: {
      description: {
        story: 'Attach the returned ref to the element you want to measure.',
      },
    },
  },
};

export const WithElement: Story = {
  render: () => {
    const ref = useRef<HTMLDivElement>(null);
    const [el, setEl] = useState<HTMLElement | null>(null);
    const { dimensions } = useDimensions(el);

    useEffect(() => {
      setEl(ref.current);
    }, []);

    return (
      <Box
        sx={{ backgroundColor: 'red' }}
        ref={ref}
      >
        <Typography variant="globalS">
          width: {dimensions.width}px · height: {dimensions.height}px
        </Typography>
      </Box>
    );
  },
  parameters: {
    docs: {
      description: {
        story:
          'Pass the element directly to the hook (see code for correct pattern).',
      },
    },
  },
};
