import { useCallback, useState } from 'react'
import { RecordingPlayer } from '../components/RecordingPlayer'
import testRecording from '../data/test-recording.json'
import styles from './RecordingTestPage.module.css'

interface RecordedFrame {
  t: number
  landmarks: { x: number; y: number; visibility?: number }[]
  worldLandmarks: { x: number; y: number; z: number; visibility?: number }[]
}

export function RecordingTestPage() {
  const [frames, setFrames] = useState<RecordedFrame[]>(testRecording)
  const [error, setError] = useState<string | null>(null)
  const [fileName, setFileName] = useState<string | null>('test-recording.json')

  const handleFile = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    setError(null)
    setFileName(file.name)
    const reader = new FileReader()
    reader.onload = () => {
      try {
        const data = JSON.parse(reader.result as string)
        if (!Array.isArray(data) || data.length === 0) {
          setError('JSON must be an array of frames')
          return
        }
        setFrames(data)
      } catch {
        setError('Invalid JSON')
      }
    }
    reader.readAsText(file)
  }, [])

  return (
    <div className={styles.root}>
      <h1 className={styles.title}>Recording Playback</h1>

      <label className={styles.fileLabel}>
        <span className={styles.fileLabelText}>
          {fileName ?? 'Load recording JSON'}
        </span>
        <input
          type="file"
          accept=".json"
          onChange={handleFile}
          className={styles.fileInput}
        />
      </label>

      {error && <p className={styles.error}>{error}</p>}

      {frames.length > 0 && (
        <div className={styles.playerWrap}>
          <RecordingPlayer frames={frames} width={640} height={480} />
        </div>
      )}
    </div>
  )
}
