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

import ExtendCard from './ExtendCard';

const meta: Meta<typeof ExtendCard> = {
  title: 'Create/ExtendCard',
  component: ExtendCard,
  parameters: {
    layout: 'padded',
  },
  argTypes: {
    clipTitle: {
      control: { type: 'text' },
      description: 'Title of the audio clip',
    },
    clipDurationSeconds: {
      control: { type: 'number', min: 1, step: 0.1 },
      description: 'Duration of the audio clip in seconds',
    },
    clipArtworkUrl: {
      control: { type: 'text' },
      description: 'URL of the clip artwork image',
    },
    extendFromSeconds: {
      control: { type: 'number', min: 0, step: 0.1 },
      description: 'Time in seconds from which to extend the audio',
    },
    setExtendFromSeconds: {
      action: 'extend from seconds changed',
      description: 'Callback when extend from time changes',
    },
    sampleAudio: {
      description:
        'Function that returns a value between 0 and 1 (indicating audio amplitude at a point in time) given a value between 0 and 1 (indicating progress through the range to be rendered)',
    },
  },
};
export default meta;

type Story = StoryObj<typeof ExtendCard>;

// Mock audio sampling function that creates a realistic waveform pattern
const createMockAudioSampler = () => {
  return (progress: number) => {
    // Create a complex waveform pattern
    const base = Math.sin(progress * 2 * Math.PI * 8) * 0.3;
    const harmonics = Math.sin(progress * 2 * Math.PI * 16) * 0.2;
    const envelope = Math.sin(progress * Math.PI) * 0.5 + 0.5;

    return Math.max(0, Math.min(1, (base + harmonics) * envelope + 0.5));
  };
};

function ExtendCardDemo(props: React.ComponentProps<typeof ExtendCard>) {
  const [extendFromSeconds, setExtendFromSeconds] = useState(
    props.extendFromSeconds
  );

  const [isPlaying, setIsPlaying] = useState(false);
  const [playbackTime, setPlaybackTime] = useState(0);

  return (
    <ExtendCard
      {...props}
      extendFromSeconds={extendFromSeconds}
      setExtendFromSeconds={setExtendFromSeconds}
      getCurrentProgress={() => playbackTime}
      setCurrentProgress={(time) => setPlaybackTime(time)}
      isPlaying={isPlaying}
      play={() => setIsPlaying(true)}
      pause={() => setIsPlaying(false)}
    />
  );
}

export const Default: Story = {
  render: (args) => <ExtendCardDemo {...args} />,
  args: {
    clipTitle: 'My Awesome Song',
    clipDurationSeconds: 30,
    clipArtworkUrl: 'https://via.placeholder.com/300x300/6366f1/ffffff?text=🎵',
    extendFromSeconds: 15,
    sampleAudio: createMockAudioSampler(),
  },
};
