import React, { useState } from 'react'
import { type Meta, type StoryObj } from '@storybook/react-vite'

import FloatingActionBar from './FloatingActionBar'
import { c } from '../../translations/LibraryTranslationService'
import { DocsTemplate } from '../../../.storybook'
import { toast } from '../Toast/Toast'
import { type MenuActionProps } from '../Menu/Menu'
import { type DropdownAction } from '../DropdownMenu/DropdownMenu'
import { type TooltipProps } from '../Tooltip/Tooltip'

const meta: Meta<typeof FloatingActionBar> = {
  title: 'Components/FloatingActionBar',
  component: FloatingActionBar,
  parameters: {
    layout: 'centered',
    design: {
      type: 'figma',
      url: 'https://www.figma.com/design/RvhKD82948FMQnh5MyCi0o/Web-Design-System?node-id=13001-6221&p=f&t=9R4mlUY42yEaNlLp-0',
    },
    docs: {
      page: () => (
        <DocsTemplate
          figmaLink='https://www.figma.com/design/RvhKD82948FMQnh5MyCi0o/Web-Design-System?node-id=13001-6221&p=f&t=9R4mlUY42yEaNlLp-0'
          description={
            <span>
              The <code>FloatingActionBar</code> component is a fixed-position
              bar that appears at the bottom of the screen, providing quick
              access to actions for selected items. It displays the count of
              selected items and a set of action buttons that can be customized
              with icons, text, and colors.
              <br />
              <br />
              On desktop, it shows up to 4 visible action buttons with
              additional actions accessible through a popover menu. On mobile,
              all actions are hidden in the popover menu for better space
              utilization.
              <br />
              <br />
              The bar automatically handles disabled states, showing gray icons
              and reduced opacity for disabled actions, while maintaining the
              specified color for enabled actions.
            </span>
          }
        />
      ),
    },
  },
  tags: ['autodocs'],
}

export default meta
type Story = StoryObj<typeof FloatingActionBar>

// Helper functions to reduce redundancy
const createToastAction =
  (text: string, type: 'info' | 'success' | 'error' = 'info') =>
  () =>
    toast({ type, message: `${text} clicked` })

const createAction = (
  text: string,
  options?: {
    icon?: string
    destructive?: boolean
    disabled?: {
      value: boolean
      tooltip?: Omit<TooltipProps, 'children'>
    }
    hasDivider?: boolean
    toastType?: 'info' | 'success' | 'error'
  },
): MenuActionProps => ({
  text,
  ...(options?.icon && { icon: options.icon as any }),
  ...(options?.destructive && { destructive: true }),
  ...(options?.disabled && {
    disabled: {
      value: options?.disabled.value,
      tooltip: options?.disabled.tooltip,
    },
  }),
  ...(options?.hasDivider && { hasDivider: true }),
  callout: createToastAction(text, options?.toastType),
})

// Shared base actions to avoid duplication
const baseActionConfigs = [
  { text: 'Export', icon: 'fileDownload', toastType: 'success' as const },
  { text: 'Edit', icon: 'pencil' },
  {
    text: 'Delete',
    icon: 'trash',
    destructive: true,
    toastType: 'error' as const,
  },
  { text: 'Share', icon: 'share2' },
  { text: 'Bulk Edit', icon: 'pencil' },
]

const Template = (args: any) => {
  const [selectedItemCount, setSelectedItemCount] = useState(5)
  const totalItemCount = 10

  return (
    <div style={{ marginTop: '50px' }}>
      <FloatingActionBar
        {...args}
        selectedItemCount={selectedItemCount}
        totalItemCount={totalItemCount}
        translate={c}
        onClose={() => setSelectedItemCount(0)}
      />
    </div>
  )
}

// Action arrays using helper functions
const defaultActions: MenuActionProps[] = [
  createAction('Export'),
  createAction('Download'),
  createAction('Bulk Edit'),
  createAction('Delete', { icon: 'trash', destructive: true }),
  createAction('Products', { icon: 'products' }),
  createAction('Share', { icon: 'share2', hasDivider: true }),
]

const iconActions: MenuActionProps[] = baseActionConfigs
  .slice(0, 3)
  .map((config) => createAction(config.text, config))

const noIconActions: MenuActionProps[] = baseActionConfigs
  .slice(0, 3)
  .map((config) => createAction(config.text, { toastType: config.toastType }))

const disabledActions: MenuActionProps[] = [
  createAction('Export', { icon: 'fileDownload', disabled: { value: true } }),
  createAction('Edit', { icon: 'pencil' }),
  createAction('Delete', { icon: 'trash', disabled: { value: true } }),
  createAction('Add', { icon: 'plus' }),
  createAction('Products', { icon: 'products' }),
  createAction('Share', { icon: 'share2', disabled: { value: true } }),
]

const submenuActions: (MenuActionProps | DropdownAction)[] = [
  createAction('Export', { icon: 'fileDownload', toastType: 'success' }),
  createAction('Share', { icon: 'share2' }),
  createAction('Bulk Edit', { icon: 'pencil' }),
  createAction('Delete', {
    icon: 'trash',
    destructive: true,
    toastType: 'error',
  }),
  {
    icon: 'archive',
    text: 'Archive',
    subMenu: [
      'Archive to Storage',
      'Archive to Vault',
      'Archive with Notes',
    ].map((text) =>
      createAction(text.replace('Archive', 'Archived'), { toastType: 'info' }),
    ),
  },
  createAction('Move', { icon: 'move' }),
  {
    icon: 'clipboard',
    text: 'Duplicate',
    subMenu: [
      {
        text: 'Duplicate Here',
        icon: 'clipboard',
        message: 'Items duplicated in current location',
      },
      {
        text: 'Duplicate to Folder',
        icon: 'folder',
        message: 'Items duplicated to selected folder',
      },
      {
        text: 'Copy Reference',
        icon: 'clipboard',
        message: 'Reference copied to clipboard',
      },
    ].map(({ text, icon, message }) => ({
      text,
      icon: icon as any,
      callout: () => toast({ type: 'success', message }),
    })),
  },
]

const confirmationActions: MenuActionProps[] = [
  createAction('Export', { icon: 'fileDownload', toastType: 'success' }),
  {
    text: 'Delete',
    icon: 'trash',
    destructive: true,
    callout: () => toast({ type: 'error', message: 'Delete clicked' }),
    confirmation: {
      type: 'black',
      header: 'Are you sure?',
      body: 'This action cannot be undone.',
      confirmCallout: () => toast({ type: 'success', message: 'Confirmed!' }),
    },
  },
]

const confirmationDisabledActions: MenuActionProps[] = [
  createAction('Export', { icon: 'fileDownload', toastType: 'success' }),
  {
    text: 'Delete',
    icon: 'trash',
    destructive: true,
    callout: () => toast({ type: 'error', message: 'Delete clicked' }),
    confirmation: {
      type: 'black',
      header: 'Are you sure?',
      body: 'This action cannot be undone.',
      confirmCallout: () => toast({ type: 'success', message: 'Confirmed!' }),
    },
    disabled: { value: true },
  },
]

const disabledActionsTooltip: MenuActionProps[] = [
  createAction('Export'),
  createAction('Delete', {
    icon: 'trash',
    disabled: {
      value: true,
      tooltip: { tooltipContent: 'This action is disabled' },
    },
  }),
]

// Story definitions
const createStory = (actions: any, extraProps?: any): Story => ({
  render: Template,
  args: { actions },
  ...(extraProps && extraProps),
})

export const Default = createStory(defaultActions)
export const WithIcons = createStory(iconActions)
export const WithoutIcons = createStory(noIconActions)
export const WithDisabledActions = createStory(disabledActions)
export const WithSubmenus = createStory(submenuActions)
export const WithConfirmation = createStory(confirmationActions)
export const WithConfirmationDisabledActions = createStory(
  confirmationDisabledActions,
)
export const WithDisabledActionsTooltip = createStory(disabledActionsTooltip)
