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

import { DocsTemplate } from '../../../.storybook'
import { LeftNav } from './LeftNav'
import { toast } from '../Toast/Toast'
import type { LeftNavLinkObj } from './LeftNav'

const meta: Meta<typeof LeftNav> = {
  title: 'Components/LeftNav',
  component: LeftNav,
  parameters: {
    layout: 'fullscreen',
    design: {
      type: 'figma',
      url: 'https://www.figma.com/design/RvhKD82948FMQnh5MyCi0o/Web-Design-System?node-id=121-356&t=jsd8kEmb1sJfCa2m-0',
    },
    docs: {
      page: () => (
        <DocsTemplate
          figmaLink='https://www.figma.com/design/RvhKD82948FMQnh5MyCi0o/Web-Design-System?node-id=121-356&t=jsd8kEmb1sJfCa2m-0'
          description={
            <span>
              The <code>LeftNav</code> component is a responsive navigation
              sidebar that provides easy access to different sections of an
              application. It includes features like:
              <ul>
                <li>
                  Logo display with optional abbreviated and isolated versions
                </li>
                <li>Navigation links with icons and permissions</li>
                <li>Breadcrumb navigation</li>
                <li>Account management popover</li>
                <li>Language selector</li>
                <li>Environment indicator</li>
                <li>Responsive design (mobile/desktop)</li>
                <li>Customizable footer</li>
              </ul>
            </span>
          }
          infoBullets={[
            <span key='first-bullet'>
              Use the <code>LeftNav</code> as the primary navigation component
              for your application.
            </span>,
            <span key='second-bullet'>
              Configure the <code>routerComponent</code> and{' '}
              <code>routerProp</code> to match your application's routing setup.
            </span>,
            <span key='third-bullet'>
              Use the <code>permissions</code> property on navigation links to
              control access based on user roles.
            </span>,
          ]}
        />
      ),
    },
  },
}
export default meta

// Helper function to generate navigation links
const generateNavLinks = (
  count: number,
  permissions: string[] = ['user'],
): LeftNavLinkObj[] => {
  const icons: IconStringList[] = [
    'actualSize',
    'anchor',
    'bag',
    'badge',
    'clockDollar',
    'bubbles',
    'bulb',
    'check',
    'barChart',
    'info',
  ]

  return Array.from({ length: count }, (_, i) => ({
    link: `/page-${i + 1}`,
    icon: icons[i % icons.length],
    name: `Page ${i + 1}`,
    permissions,
    footerLink: i >= 7, // Last 3 links will be footer links
  }))
}

// Base template with common props
const Template = (args) => {
  const popoverOptions = [
    {
      icon: 'maleUser' as const,
      label: 'My Profile',
      callout: () => toast({ type: 'success', message: 'My Profile clicked' }),
    },
    {
      icon: 'info' as const,
      label: 'Privacy Policy',
      callout: () =>
        toast({ type: 'success', message: 'Privacy Policy clicked' }),
    },
    {
      icon: 'eyeglasses' as const,
      label: 'View As',
      callout: () => undefined,
      hide: true,
    },
    {
      icon: 'logout' as const,
      label: 'Logout',
      callout: () => toast({ type: 'success', message: 'Logout clicked' }),
    },
  ]

  return (
    <LeftNav
      routerComponent={Link}
      routerProp='to'
      environment='production'
      breadcrumbs={[
        { link: '/page-1', name: 'Page 1' },
        { link: '/page-2', name: 'Page 2' },
      ]}
      leftNavLinks={generateNavLinks(10)}
      logo={{
        url: 'https://images.pattern.com/pattern_exp_logos/predict.svg',
        abbreviatedUrl:
          'https://images.pattern.com/pattern_exp_logos/predict-abbr.svg',
        isolatedUrl:
          'https://images.pattern.com/pattern_exp_logos/predict-isolated.svg',
      }}
      accountPopoverProps={{
        name: 'Pat Ern',
        options: popoverOptions,
      }}
      userPermissions={['admin', 'user']}
      navigate={() =>
        toast({ type: 'success', message: 'Navigate to Home Page Clicked' })
      }
      footer={() => (
        <>
          <div className='text-2xs px-2 text-center text-purple'>
            Footer content here
          </div>
          <LeftNav.Divider />
        </>
      )}
      {...args}
    />
  )
}

type Story = StoryObj<typeof LeftNav>

// Basic usage
export const Basic: Story = {
  render: Template,
}

// Different environments
export const Development: Story = {
  render: Template,
  args: {
    environment: 'development',
  },
}

export const Staging: Story = {
  render: Template,
  args: {
    environment: 'staging',
  },
}

export const Demo: Story = {
  render: Template,
  args: {
    environment: 'demo',
  },
}

// Mobile variations
export const MobileHeaderChildren: Story = {
  render: Template,
  args: {
    mobileProps: {
      mobileHeaderChildren: <span>Optional Header</span>,
    },
  },
}

export const MobileHamburgerAtRight: Story = {
  render: Template,
  args: {
    mobileProps: {
      mobileHeaderChildren: <span>Optional Header</span>,
      rightHamburgerMenu: true,
    },
  },
}

// Height offset
export const HeightOffset: Story = {
  render: Template,
  args: {
    heightOffset: 100,
  },
}

// Permission-based navigation
export const AdminOnlyLinks: Story = {
  render: Template,
  args: {
    leftNavLinks: generateNavLinks(5, ['admin']),
    userPermissions: ['admin'],
  },
}

// Language selector variations
export const LanguageSelector: Story = {
  render: Template,
  args: {
    languageConfig: {
      selectedLanguage: 'en',
      supportedLanguages: ['en', 'es', 'fr', 'pl', 'zh'],
      setLanguage: (language) => {
        toast({ type: 'success', message: `Language changed to ${language}` })
      },
    },
  },
}

// Custom footer
export const CustomFooter: Story = {
  render: Template,
  args: {
    footer: () => (
      <div className='text-2xs px-2 text-center text-purple'>
        Custom footer content
      </div>
    ),
  },
}

// Hidden logo
export const HiddenLogo: Story = {
  render: Template,
  args: {
    hideLogo: true,
  },
}

// Disabled account
export const DisabledAccount: Story = {
  render: Template,
  args: {
    accountPopoverProps: {
      disabled: true,
      name: 'Pattern',
      options: [],
    },
  },
}

export const HiddenCopyright: Story = {
  render: Template,
  args: {
    hideCopyright: true,
  },
}
