import React from 'react'
import type { ExamplesData } from './Examples'
import { groupByNameAndVariant } from './galleryUtils'
import ExampleMetadata from './ExampleMetadata'
import ExampleDetailsSection from './ExampleDetailsSection'
import ExampleVariantSelector from './ExampleVariantSelector'

interface GalleryProps {
  selectedModel: string
  selectedAttack: string
  examples: {
    [model: string]: {
      [attack: string]: ExamplesData[]
    }
  }
}

const VideoGallery: React.FC<GalleryProps> = ({ selectedModel, selectedAttack, examples }) => {
  const exampleItems = examples[selectedModel][selectedAttack]
  const grouped = groupByNameAndVariant(exampleItems)
  const videoNames = Object.keys(grouped)
  const [selectedVideo, setSelectedVideo] = React.useState(videoNames[0] || '')
  const variants = grouped[selectedVideo] || {}
  const variantKeys = Object.keys(variants)
  const [selectedVariant, setSelectedVariant] = React.useState(variantKeys[0] || '')

  React.useEffect(() => {
    setSelectedVariant(variantKeys[0] || '')
  }, [selectedVideo])

  if (!videoNames.length) {
    return (
      <div className="w-full mt-12 flex items-center justify-center">
        <div className="text-gray-500">
          No video examples available. Please select another model and attack.
        </div>
      </div>
    )
  }

  return (
    <div className="w-full overflow-auto" style={{ minHeight: '100vh' }}>
      <div className="example-display">
        <div className="mb-4">
          <fieldset className="fieldset">
            <legend className="fieldset-legend">Video Example</legend>
            <select
              className="select select-bordered"
              value={selectedVideo || ''}
              onChange={(e) => {
                setSelectedVideo(e.target.value || '')
              }}
            >
              {videoNames.map((name) => (
                <option key={name} value={name}>
                  {name}
                </option>
              ))}
            </select>
          </fieldset>
        </div>
        {selectedVideo && selectedVariant && variants[selectedVariant] && (
          <>
            <ExampleVariantSelector
              variantKeys={variantKeys}
              selectedVariant={selectedVariant}
              setSelectedVariant={setSelectedVariant}
            />
            <ExampleMetadata metadata={variants[selectedVariant].metadata || {}} />
            <ExampleDetailsSection>
              <div className="flex flex-col items-center gap-4">
                {variants[selectedVariant].video_url && (
                  <video
                    controls
                    src={variants[selectedVariant].video_url}
                    className="example-video"
                    style={{ maxWidth: 400, maxHeight: 300 }}
                  />
                )}
              </div>
            </ExampleDetailsSection>
          </>
        )}
      </div>
    </div>
  )
}

export default VideoGallery
