import { useState } from 'react';
import { apiDownloaderDownloadRetrieve, apiDownloaderDownloadCreate } from '@/api/generated/public/downloader';
import { type VideoInfoResponse } from '@/api/generated/public/models';


export default function Downloader() {
  const [videoUrl, setVideoUrl] = useState('');
  const [videoInfo, setVideoInfo] = useState<null | VideoInfoResponse>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<null | { error: string }>(null);

  async function retriveVideoInfo() {
    setIsLoading(true);
    setError(null);
    try {
      const info = await apiDownloaderDownloadRetrieve({ url: videoUrl });
      setVideoInfo(info);
    } catch (err: any) {
      setError({ error: err.message || 'Failed to retrieve video info' });
    } finally {
      setIsLoading(false);
    }

    console.log('Retrieving video info for URL:', videoUrl);
    console.log('Retrieved video info:', videoInfo);

  }


  return (
    <div className="p-6">
      <h1 className="text-2xl font-bold mb-4">Video Downloader</h1>

      <input
        type="text"
        value={videoUrl}
        onChange={(e) => setVideoUrl(e.target.value)}
        placeholder="Paste video URL here"
        className="w-full p-2 border rounded mb-4"
      />

      <button onClick={retriveVideoInfo}>Retrieve options</button>

      {isLoading && <p>Loading video info...</p>}
      
      {error && <p className="text-red-500">Error: {error?.error}</p>}
      
      {videoInfo && (
        <div className="mt-4">
          <h2 className="text-xl font-semibold">{videoInfo.title}</h2>
          {videoInfo.thumbnail && (
            <img src={videoInfo.thumbnail} alt={videoInfo.title} className="mt-2 max-w-md" />
          )}
          <p className="mt-2">Duration: {videoInfo.duration}s</p>
          
          <h3 className="mt-4 font-semibold">Available Video Qualities:</h3>
          <ul>
            {videoInfo.video_resolutions?.map((res) => (
              <li key={res}>{res}</li>
            ))}
          </ul>
          
          <h3 className="mt-4 font-semibold">Available Audio Qualities:</h3>
          <ul>
            {videoInfo.audio_resolutions?.map((res) => (
              <li key={res}>{res}</li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}