import type { Meta, StoryObj } from '@storybook/react';
import React, { useCallback, useState } from 'react';
import { fn } from 'storybook/test';

import NavTab from './NavTab';

type PagePropsAndCustomArgs = Pick<
  React.ComponentProps<typeof NavTab>,
  'active' | 'size' | 'href' | 'className' | 'children' | 'onClick'
> & { onClick?: React.MouseEventHandler };

const meta: Meta<PagePropsAndCustomArgs> = {
  title: 'components/NavTab',
  component: NavTab,
  argTypes: {
    active: {
      control: { type: 'boolean' },
    },
    href: {
      control: { type: 'text' },
    },
    className: {
      control: { type: 'text' },
    },
    children: {
      control: { type: 'text' },
    },
    size: {
      options: ['Default', 'Small'],
      mapping: {
        Default: 'default',
        Small: 'sm',
      },
    },
  },
};

export default meta;
type Story = StoryObj<PagePropsAndCustomArgs>;

export const Link: Story = {
  args: {
    children: 'Link Navigation Tab',
    href: 'https://suno.com',
  },
};

export const Button: Story = {
  args: {
    children: 'Button Navigation Tab',
    onClick: fn(),
  },
};

export const ActiveState: Story = {
  args: {
    active: true,
    children: 'Active Navigation Tab',
  },
};

function ContainerDemo(props: PagePropsAndCustomArgs) {
  const { onClick, ...restProps } = props;
  const [isActive, setIsActive] = useState(false);
  const handleClick = useCallback<React.MouseEventHandler>(
    (e) => {
      setIsActive((prevIsActive) => !prevIsActive);
      onClick?.(e);
    },
    [onClick]
  );
  return (
    <NavTab active={isActive} onClick={handleClick} {...restProps}>
      <div>
        <h1 className='text-lg font-medium'>Heading, large</h1>
        <p className='text-sm'>Content, in charge</p>
      </div>
    </NavTab>
  );
}

export const Container: Story = {
  render: (args) => <ContainerDemo {...args} />,
  argTypes: {
    children: { table: { disable: true } },
  },
};

function TabGroupDemo(props: PagePropsAndCustomArgs) {
  const { onClick, ...restProps } = props;
  const [currentTab, setCurrentTab] = useState('Home');
  const handleClick = useCallback(
    (e: React.MouseEvent<HTMLButtonElement>, name: string) => {
      setCurrentTab(name);
      onClick?.(e);
    },
    [onClick]
  );
  return (
    <div className='flex flex-col'>
      {['Home', 'Create', 'Library', 'Explore', 'Search'].map((name) => (
        <NavTab
          key={name}
          {...restProps}
          href=''
          active={currentTab === name}
          onClick={(e: any) => handleClick(e, name)}
        >
          {name}
        </NavTab>
      ))}
    </div>
  );
}

export const TabGroup: Story = {
  render: (args) => <TabGroupDemo {...args} />,
  args: {
    onClick: fn(),
  },
  argTypes: {
    active: { table: { disable: true } },
    children: { table: { disable: true } },
  },
};
