import type { Meta, StoryObj } from '@storybook/react-vite'
import { ChevronLeftIcon, ChevronRightIcon } from '@radix-ui/react-icons'
import { cn } from '@lib/utils'

import { Button } from '@components/ui/button/button'

import { ContentFrame } from './content-frame'
import { expect, userEvent, screen } from 'storybook/test'
import { useState } from 'react'
import { Modal } from '@components/ui/modal/modal'
import { Badge } from '@components/ui/badge/badge'

const meta = {
  title: 'ContentFrame',
  component: ContentFrame,
  tags: ['autodocs'],
  parameters: {
    layout: 'centered',
  },
  argTypes: {
    title: {
      control: 'text',
    },
    variant: {
      control: 'select',
      options: ['default', 'inverted'],
    },
  },
} satisfies Meta<typeof ContentFrame>
export default meta

type Story = StoryObj<typeof meta>

export const Default: Story = {
  args: {
    title: 'Title',
    variant: 'default',
  },
  render: (args) => (
    <div className="w-[350px]">
      <ContentFrame {...args}>
        <div className="p-2">Content inside the frame</div>
      </ContentFrame>
    </div>
  ),
  play: async () => {
    expect(screen.getByText('Title')).toBeVisible()
    expect(screen.getByText('Content inside the frame')).toBeVisible()
    const frame = screen.getByText('Content inside the frame').closest('div')
  },
}

export const Variants: Story = {
  args: { title: '' },
  render: () => (
    <div className="flex gap-2">
      <div className="w-[200px]">
        <ContentFrame title="default" variant="default">
          <div className="p-2">Content</div>
        </ContentFrame>
      </div>
      <div className="w-[200px]">
        <ContentFrame title="inverted" variant="inverted">
          <div className="p-2">Content</div>
        </ContentFrame>
      </div>
    </div>
  ),
}

export const WithTitleLink: Story = {
  args: {
    title: '',
    titleLink: (
      <a href="https://example.com/" target="_blank" rel="noopener noreferrer">
        <h2 className="text-xl overflow-hidden text-ellipsis whitespace-nowrap">Title with Link</h2>
      </a>
    ),
  },
  render: (args) => (
    <div className="w-[350px]">
      <ContentFrame {...args}>
        <div className="p-2">Content inside the frame</div>
      </ContentFrame>
    </div>
  ),
  play: async () => {
    // Check that the title link exists and is correct
    const link = screen.getByRole('link', { name: /title with link/i })
    expect(link).toHaveAttribute('href', 'https://example.com/')
  },
}

export const CollapsibleAndExpandable: Story = {
  args: { title: '' },
  render: () => {
    const dummyText =
      'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam rutrum laoreet erat ac sodales. Pellentesque nec nunc in ipsum tincidunt congue sit amet in augue. Sed interdum consequat arcu, ac tempor nisl eleifend sed. Mauris gravida ipsum orci, sed vestibulum nisl commodo in. Aliquam ut dolor dui. Donec fermentum viverra faucibus. In aliquet erat et quam ornare, et accumsan magna ornare. Suspendisse potenti. Etiam a elit dui. Mauris et lectus vel metus lobortis luctus. Vestibulum elementum sit amet augue vel rutrum. Aenean sem turpis, viverra hendrerit consequat eget, vulputate sed nunc. Pellentesque sollicitudin diam nunc, vel pretium massa mattis at. Curabitur fringilla convallis mollis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam rutrum laoreet erat ac sodales. Pellentesque nec nunc in ipsum tincidunt congue sit amet in augue. Sed interdum consequat arcu, ac tempor nisl eleifend sed. Mauris gravida ipsum orci, sed vestibulum nisl commodo in. Aliquam ut dolor dui. Donec fermentum viverra faucibus. In aliquet erat et quam ornare, et accumsan magna ornare. Suspendisse potenti. Etiam a elit dui. Mauris et lectus vel metus lobortis luctus. Vestibulum elementum sit amet augue vel rutrum. Aenean sem turpis, viverra hendrerit consequat eget, vulputate sed nunc. Pellentesque sollicitudin diam nunc, vel pretium massa mattis at. Curabitur fringilla convallis mollis. '

    const [isCollapsed, setIsCollapsed] = useState(false)
    const [isExpanded, setIsExpanded] = useState(false)
    return (
      <>
        <div className="w-[350px]">
          <div
            className={cn(
              'relative h-[250px]',
              isCollapsed ? 'min-w-[60px] max-w-[60px]' : 'min-w-[350px] max-w-[350px]',
            )}
          >
            <ContentFrame
              title="Collapsible and Expandable"
              variant="inverted"
              collapsed={isCollapsed}
              onExpand={() => setIsExpanded(true)}
            >
              <div className="p-2">{dummyText}</div>
            </ContentFrame>
            <Button
              title={isCollapsed ? 'Show normal' : 'Collapse'}
              variant="neutral"
              size="iconSm"
              className="absolute top-1/2 right-0 transform -translate-y-1/2 translate-x-1/4 z-10 rounded-full bg-muted-foreground text-background"
              onClick={() => setIsCollapsed(!isCollapsed)}
            >
              {isCollapsed ? <ChevronRightIcon /> : <ChevronLeftIcon />}
            </Button>
          </div>
        </div>
        <Modal isOpen={isExpanded} setIsOpen={setIsExpanded} title="Collapsible and Expandable">
          <div className="p-2">{dummyText}</div>
        </Modal>
      </>
    )
  },
  play: async () => {
    // Collapse the frame
    const collapseBtn = screen.getByRole('button', { name: /collapse/i })
    await userEvent.click(collapseBtn)
    // After collapse, check that the ChevronRightIcon is rendered (collapsed state)
    expect(screen.getByRole('button', { name: /show normal/i })).toBeVisible()
    const expandModal = screen.getByText('Collapsible and Expandable')
    expect(expandModal).toBeVisible()
  },
}

export const WithControlsAndIndicators: Story = {
  args: {
    title: '',
  },
  render: (args) => {
    const [newsUnread, setNewsUnread] = useState(true)
    return (
      <div className="w-[350px]">
        <ContentFrame
          {...args}
          title={newsUnread ? 'Unread News' : 'No unread News'}
          controls={[
            <Button key="c1" variant="outline" size="sm" onClick={() => setNewsUnread(!newsUnread)}>
              {newsUnread ? 'Read all' : 'Unread all'}
            </Button>,
          ]}
          indicators={
            newsUnread
              ? [
                  <Badge
                    data-testid="pill-label"
                    key="i1"
                    className="self-center bg-(--ring) rounded-full h-5 text-background font-bold px-2"
                  >
                    3
                  </Badge>,
                ]
              : []
          }
        >
          <div className="p-2">
            {newsUnread ? (
              <>
                News 1<br />
                News 2<br />
                News 3
              </>
            ) : (
              'No new content'
            )}
          </div>
        </ContentFrame>
      </div>
    )
  },
  play: async () => {
    // Check for control button
    expect(screen.getByRole('button', { name: /read all|unread all/i })).toBeVisible()
    // Check for indicator badge
    expect(screen.getByTestId('pill-label')).toBeVisible()
  },
}
