import type { Meta, StoryObj } from '@storybook/react';
import { useState } from 'react';

import { VideoFrameTimeline } from './VideoFrameTimeline';

const meta: Meta<typeof VideoFrameTimeline> = {
  title: 'Components/Video/VideoFrameTimeline',
  component: VideoFrameTimeline,
  parameters: {
    layout: 'centered',
    docs: {
      description: {
        component:
          'A timeline component that displays video frames as a filmstrip and allows users to scrub through the video timeline. Features performance-optimized canvas rendering and smooth timeline interaction.',
      },
    },
  },
  tags: ['autodocs'],
  argTypes: {
    videoUrl: {
      control: 'text',
      description: 'URL of the video to display in the timeline',
    },
    videoDuration: {
      control: 'number',
      description: 'Duration of the video in milliseconds',
    },
    currentTimestamp: {
      control: 'number',
      description: 'Current timestamp position in the video timeline',
    },
    onTimestampChange: {
      action: 'onTimestampChange',
      description: 'Callback function called when the timestamp changes',
    },
    onThumbnailUpdate: {
      action: 'onThumbnailUpdate',
      description: 'Callback function called when thumbnail updates',
    },
    videoRef: {
      control: false,
      description: 'External video element reference',
    },
    className: {
      control: 'text',
      description: 'Additional CSS classes to apply',
    },
  },
};

export default meta;
type Story = StoryObj<typeof meta>;

// Mock video URLs for different test scenarios
const MOCK_VIDEO_URLS = {
  short: 'https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_1mb.mp4',
  long: 'https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4',
  medium: 'https://sample-videos.com/zip/10/mp4/SampleVideo_1280x720_2mb.mp4',
};

const MOCK_VIDEO_DURATIONS = {
  short: 30000, // 30 seconds
  medium: 120000, // 2 minutes
  long: 596000, // ~10 minutes
};

const InteractiveDemo = (args: any) => {
  const [currentTimestamp, setCurrentTimestamp] = useState(5000); // Start at 5 seconds

  const handleTimestampChange = (timestamp: number) => {
    setCurrentTimestamp(timestamp);
  };

  const handleThumbnailUpdate = (thumbnailUrl: string) => {
    console.log('Thumbnail updated:', thumbnailUrl);
  };

  return (
    <div className='w-full max-w-2xl'>
      <div className='mb-4 rounded-lg bg-gray-100 p-4'>
        <h3 className='mb-2 font-semibold'>Timeline Controls</h3>
        <div className='flex items-center gap-4'>
          <span className='text-sm text-gray-600'>
            Current: {Math.round(currentTimestamp / 1000)}s
          </span>
          <button
            onClick={() => setCurrentTimestamp(0)}
            className='rounded bg-accent-blue px-3 py-1 text-sm text-white hover:bg-blue-600'
            type='button'
          >
            Reset to Start
          </button>
          <button
            onClick={() =>
              setCurrentTimestamp((args.videoDuration || 30000) / 2)
            }
            className='rounded bg-accent-green px-3 py-1 text-sm text-white hover:bg-green-600'
            type='button'
          >
            Go to Middle
          </button>
          <button
            onClick={() => setCurrentTimestamp(args.videoDuration || 30000)}
            className='rounded bg-accent-red px-3 py-1 text-sm text-white hover:bg-red-600'
            type='button'
          >
            Go to End
          </button>
        </div>
      </div>
      <VideoFrameTimeline
        videoUrl={args.videoUrl || MOCK_VIDEO_URLS.short}
        videoDuration={args.videoDuration || MOCK_VIDEO_DURATIONS.short}
        currentTimestamp={currentTimestamp}
        onTimestampChange={handleTimestampChange}
        onThumbnailUpdate={handleThumbnailUpdate}
        className={args.className}
      />
    </div>
  );
};

export const Default: Story = {
  render: InteractiveDemo,
  args: {
    videoUrl: MOCK_VIDEO_URLS.short,
    videoDuration: MOCK_VIDEO_DURATIONS.short,
  },
};

export const ShortVideo: Story = {
  render: InteractiveDemo,
  args: {
    videoUrl: MOCK_VIDEO_URLS.short,
    videoDuration: MOCK_VIDEO_DURATIONS.short,
  },
  parameters: {
    docs: {
      description: {
        story:
          'A short video timeline (30 seconds) for testing basic functionality.',
      },
    },
  },
};

export const MediumVideo: Story = {
  render: InteractiveDemo,
  args: {
    videoUrl: MOCK_VIDEO_URLS.medium,
    videoDuration: MOCK_VIDEO_DURATIONS.medium,
  },
  parameters: {
    docs: {
      description: {
        story:
          'A medium-length video timeline (2 minutes) for testing performance.',
      },
    },
  },
};

export const LongVideo: Story = {
  render: InteractiveDemo,
  args: {
    videoUrl: MOCK_VIDEO_URLS.long,
    videoDuration: MOCK_VIDEO_DURATIONS.long,
  },
  parameters: {
    docs: {
      description: {
        story:
          'A long video timeline (10 minutes) for testing performance and memory usage.',
      },
    },
  },
};

export const WithoutVideo: Story = {
  render: InteractiveDemo,
  args: {
    videoUrl: '',
    videoDuration: 0,
  },
  parameters: {
    docs: {
      description: {
        story:
          'Timeline in a state where no video is loaded, showing loading state.',
      },
    },
  },
};

const DifferentStartPositionsDemo = () => {
  const [currentTimestamp, setCurrentTimestamp] = useState(15000); // Start at 15 seconds

  const handleTimestampChange = (timestamp: number) => {
    setCurrentTimestamp(timestamp);
  };

  return (
    <div className='w-full max-w-2xl space-y-4'>
      <div className='rounded-lg bg-gray-100 p-4'>
        <h3 className='mb-2 font-semibold'>
          Timeline with Different Start Position
        </h3>
        <p className='text-sm text-gray-600'>
          This timeline starts at 15 seconds to test timeline behavior with
          different initial positions.
        </p>
      </div>
      <VideoFrameTimeline
        videoUrl={MOCK_VIDEO_URLS.medium}
        videoDuration={MOCK_VIDEO_DURATIONS.medium}
        currentTimestamp={currentTimestamp}
        onTimestampChange={handleTimestampChange}
      />
    </div>
  );
};

export const DifferentStartPositions: Story = {
  render: DifferentStartPositionsDemo,
  parameters: {
    docs: {
      description: {
        story:
          'Timeline starting at different timestamp positions to test timeline behavior.',
      },
    },
  },
};

export const CustomStyling: Story = {
  render: InteractiveDemo,
  args: {
    videoUrl: MOCK_VIDEO_URLS.short,
    videoDuration: MOCK_VIDEO_DURATIONS.short,
    className: 'border-2 border-blue-500 rounded-lg p-2',
  },
  parameters: {
    docs: {
      description: {
        story: 'Timeline with custom CSS classes for styling customization.',
      },
    },
  },
};

const PerformanceTestDemo = () => {
  const [currentTimestamp, setCurrentTimestamp] = useState(0);

  const handleTimestampChange = (timestamp: number) => {
    setCurrentTimestamp(timestamp);
  };

  return (
    <div className='w-full max-w-2xl space-y-4'>
      <div className='rounded-lg bg-gray-100 p-4'>
        <h3 className='mb-2 font-semibold'>Performance Test</h3>
        <p className='text-sm text-gray-600'>
          This timeline is optimized for performance with throttled updates and
          smooth rendering.
        </p>
      </div>
      <div>
        <VideoFrameTimeline
          videoUrl={MOCK_VIDEO_URLS.long}
          videoDuration={MOCK_VIDEO_DURATIONS.long}
          currentTimestamp={currentTimestamp}
          onTimestampChange={handleTimestampChange}
        />
      </div>
    </div>
  );
};

export const PerformanceTest: Story = {
  render: PerformanceTestDemo,
  parameters: {
    docs: {
      description: {
        story:
          'Performance-optimized timeline with throttled updates and smooth rendering.',
      },
    },
  },
};
