import {useRef} from 'react'

import {fn} from 'storybook/test'

import {VideoPlayer, VideoPlayerRef} from '../components/atoms/video-player'

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

const meta: Meta<typeof VideoPlayer> = {
  title: 'Atoms/VideoPlayer',
  component: VideoPlayer,
  parameters: {
    layout: 'padded',
  },
  args: {
    onPlay: fn(),
    onPause: fn(),
    onEnded: fn(),
    onReady: fn(),
  },
  argTypes: {
    src: {
      control: 'text',
    },
    format: {
      control: 'select',
      options: ['video/mp4', 'video/webm', 'video/ogg'],
    },
    poster: {
      control: 'text',
    },
    width: {
      control: 'number',
    },
    height: {
      control: 'number',
    },
    muted: {
      control: 'boolean',
    },
    autoplay: {
      control: 'boolean',
    },
    playButtonComponent: {
      control: 'text',
    },
  },
  tags: ['autodocs'],
}

export default meta
type Story = StoryObj<typeof meta>

const SAMPLE_VIDEO_MP4 =
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4'
const SAMPLE_POSTER =
  'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg'

export const FixedWidth: Story = {
  args: {
    src: SAMPLE_VIDEO_MP4,
    width: 300,
  },
}

export const FixedHeight: Story = {
  args: {
    src: SAMPLE_VIDEO_MP4,
    height: 200,
  },
}

export const WithPoster: Story = {
  args: {
    src: SAMPLE_VIDEO_MP4,
    poster: SAMPLE_POSTER,
    width: 300,
  },
}

export const WithCustomPlayButton: Story = {
  args: {
    src: SAMPLE_VIDEO_MP4,
    poster: SAMPLE_POSTER,
    width: 300,
    playButtonComponent: (
      <div className="bg-blue-500 text-white rounded-full p-4 shadow-lg">
        <svg viewBox="0 0 24 24" className="w-8 h-8" fill="currentColor">
          <path d="M8 5v14l11-7z" />
        </svg>
      </div>
    ),
  },
}

const WithImperativeControlsComponent = (args: any) => {
  const videoRef = useRef<VideoPlayerRef>(null)

  return (
    <div className="space-y-4 flex flex-col items-center">
      <VideoPlayer ref={videoRef} {...args} />
      <div className="flex gap-2">
        <button
          type="button"
          className="px-4 py-2 bg-primary text-white rounded"
          onClick={() => videoRef.current?.play()}
        >
          Play
        </button>
        <button
          type="button"
          className="px-4 py-2 bg-red-400 text-white rounded"
          onClick={() => videoRef.current?.pause()}
        >
          Pause
        </button>
      </div>
    </div>
  )
}

export const WithImperativeControls: Story = {
  render: WithImperativeControlsComponent,
  args: {
    src: SAMPLE_VIDEO_MP4,
    poster: SAMPLE_POSTER,
    width: 300,
  },
}
