import React, { useEffect, useState } from 'react'
import type { Meta, StoryObj } from '@storybook/react-vite'
import { useLocation, useNavigate } from 'react-router-dom'

import Button from '../Button/Button'
import FormFooter from '../Form/FormFooter'
import Picker from '../Picker/Picker'
import { SideDrawer } from '../SideDrawer/SideDrawer'
import {
  addNewBreadcrumb,
  breadcrumbNavigation,
} from './Common/BreadcrumbsService'
import Breadcrumbs from './Breadcrumbs'
import { type BreadcrumbType } from './Common/BreadcrumbTypes'
import { DocsTemplate } from '../../../.storybook'

const meta: Meta<typeof Breadcrumbs> = {
  title: 'Components/Breadcrumbs',
  component: Breadcrumbs,
  parameters: {
    design: {
      type: 'figma',
      url: 'https://www.figma.com/design/RvhKD82948FMQnh5MyCi0o/Web-Design-System?node-id=238-3430&t=47NWXExemisHjPrj-0',
    },
    docs: {
      page: () => (
        <DocsTemplate
          figmaLink='https://www.figma.com/design/RvhKD82948FMQnh5MyCi0o/Web-Design-System?node-id=238-3430&t=47NWXExemisHjPrj-0'
          description={
            <span>
              <code>Breadcrumbs</code> are a navigational aid that visually
              represents the user's path and helps them keep track of their page
              history within the application. <code>Breadcrumbs</code> enhance
              the user experience by providing context, aiding navigation, and
              allowing easy backtracking.
            </span>
          }
        />
      ),
    },
  },
}
export default meta

type Story = StoryObj<typeof Breadcrumbs>

const breadcrumbs = [
  { name: 'Level 1', link: '/level-1' },
  {
    name: 'Level 2',
    link: '/level-2',
  },
  {
    name: 'Level 3',
    link: '/level-3',
  },
]

const Template: Story = {
  render: function Render(args) {
    const [breadcrumbs, setBreadcrumbs] = useState(args.breadcrumbs)
    const [isOpen, setIsOpen] = useState(false)
    const location = useLocation()
    const navigate = useNavigate()

    const breadcrumbTypes = {
      standardBreadcrumb: {
        name: `Level ${breadcrumbs.length + 1}`,
        link: `/level-${breadcrumbs.length + 1}`,
      },
      tabBreadcrumb: {
        name: breadcrumbs[breadcrumbs.length - 1].name,
        link: `/new-link-${breadcrumbs.length + 1}`,
        changeType: 'tab',
      },
      rootLevelBreadcrumb: {
        name: `Level 1`,
        link: `/level-1`,
        changeType: 'rootLevel',
      },
    }

    const breadcrumbOptions = [
      {
        id: 1,
        text: 'Standard',
        value: 'standardBreadcrumb',
      },
      {
        id: 2,
        text: 'Tab',
        value: 'tabBreadcrumb',
      },
      {
        id: 3,
        text: 'Root Level',
        value: 'rootLevelBreadcrumb',
      },
    ]

    const [activeBreadcrumbOption, setActiveBreadcrumbOption] = useState(
      breadcrumbOptions[0],
    )

    const reset = () => {
      navigate(args.breadcrumbs[args.breadcrumbs.length - 1].link)
      setBreadcrumbs(args.breadcrumbs)
    }

    const updateSelected = (value: string) => {
      const activeOption = breadcrumbOptions.find(
        (item) => item.value === value,
      )
      setActiveBreadcrumbOption(activeOption || breadcrumbOptions[0])
    }

    const navCallout = (breadcrumb: BreadcrumbType) => {
      setBreadcrumbs(
        breadcrumbNavigation({
          breadcrumb,
          breadcrumbs,
        }),
      )
    }

    useEffect(() => {
      if (breadcrumbs) {
        const index = breadcrumbs.findIndex(
          (crumb) => crumb.link === location.pathname,
        )
        if (index >= 0) {
          setBreadcrumbs((prevBreadcrumbs) => {
            const newBreadcrumbs = prevBreadcrumbs.slice(0, index + 1)
            if (prevBreadcrumbs.length !== newBreadcrumbs.length) {
              return newBreadcrumbs
            }
            return prevBreadcrumbs
          })
        }
      }
    }, [breadcrumbs, location.pathname])

    return (
      <div className='flex flex-col items-center gap-4'>
        <Breadcrumbs {...args} breadcrumbs={breadcrumbs} callout={navCallout} />
        <div className='flex gap-4'>
          <Button onClick={reset}>Reset Breadcrumbs</Button>
          <Button styleType='primary' onClick={() => setIsOpen(true)}>
            Add Breadcrumb
          </Button>
          <SideDrawer
            isOpen={isOpen}
            closeCallout={() => setIsOpen(false)}
            headerContent='Add A Breadcrumb'
            footerContent={({ close }) => (
              <FormFooter
                cancelButtonProps={{
                  onClick: () => {
                    close()
                  },
                }}
                saveButtonProps={{
                  onClick: () => {
                    setBreadcrumbs(
                      addNewBreadcrumb({
                        breadcrumb:
                          breadcrumbTypes[activeBreadcrumbOption.value],
                        breadcrumbs,
                      }),
                    )
                    close()
                  },
                  children: 'Add Breadcrumb',
                }}
              />
            )}
          >
            <Picker
              options={breadcrumbOptions}
              labelText='Breadcrumb Type'
              state={activeBreadcrumbOption}
              stateName='value'
              callout={(_, value) => updateSelected(value)}
            />
          </SideDrawer>
        </div>
      </div>
    )
  },
}

export const Basic: Story = {
  ...Template,
  args: {
    breadcrumbs: [
      { name: 'Level 1', link: '/level-1' },
      {
        name: 'Level 2',
        link: '/level-2',
      },
      {
        name: 'Level 3',
        link: '/level-3',
      },
    ],
  },
}

export const ManyBreadcrumbs: Story = {
  ...Template,
  args: {
    breadcrumbs: [
      ...breadcrumbs,
      {
        name: 'Level 4',
        link: '/level-4',
      },
      {
        name: 'Level 5',
        link: '/level-5',
      },
    ],
  },
}

export const LongBreadcrumbName: Story = {
  ...Template,
  args: {
    breadcrumbs: [
      {
        name: 'Level 1',
        link: '/level-1',
      },
      {
        name: 'Level 2 with a long breadcrumb name for testing purposes',
        link: '/level-2',
      },
      {
        name: 'Level 3',
        link: '/level-3',
      },
    ],
  },
}

export const CharacterLimit: Story = {
  ...Template,
  args: {
    breadcrumbs: [
      {
        name: 'Level 1 With a Longer Title',
        link: '/level-1',
      },
      {
        name: 'Level 2 with a long breadcrumb name for testing purposes',
        link: '/level-2',
      },
      {
        name: 'Level 3 With a Longer Title',
        link: '/level-3',
      },
    ],
    characterLimit: 12,
  },
}

export const CustomBackButtonText: Story = {
  ...Template,
  args: {
    breadcrumbs: breadcrumbs,
    backButtonProps: {
      text: 'custom text',
    },
  },
}
CustomBackButtonText.storyName = 'Custom Back Button Text (Desktop Only)'

export const BackButtonConfirmation: Story = {
  ...Template,
  args: {
    breadcrumbs: breadcrumbs,
    backButtonProps: {
      confirmation: {
        type: 'red',
        header: 'Are you sure?',
        body: 'Are you sure you want to go back to the previous page?',
      },
    },
  },
}

export const TextUnderlineCharacterLimit: Story = {
  ...Template,
  args: {
    breadcrumbs: [
      {
        name: 'Level 1',
        link: '/level-1',
      },
      {
        name: 'Level 2 with a long breadcrumb name for testing purposes',
        link: '/level-2',
      },
      {
        name: '0_0FJSALK D-1_LKAJFK LDS.jpg',
        link: '/level-3',
      },
    ],
    textUnderlineCharacterLimit: 15,
  },
}
