import React, { useState, FormEvent } from 'react';

interface InputData {
  prompt: string;
  width: number;
  height: number;
  steps: number;
  fps: number;
  seed?: number;
}

const IndexPage = () => {
  const [inputData, setInputData] = useState<InputData>({
    prompt: '',
    width: 1024,
    height: 576,
    steps: 40,
    fps: 15,
    seed: undefined,
  });
  const [output, setOutput] = useState<any>(null);
  const [isLoading, setIsLoading] = useState(false);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setInputData((prevData) => ({ ...prevData, [name]: value }));
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    console.log("Making API call with payload:", inputData);
    
    try {
      const response = await fetch('/api/replicate', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(inputData),
      });
  
      const result = await response.json();
      console.log("API call response:", result);
  
      if (response.ok) {
        setIsLoading(false);
        setOutput(result.prediction);  // Updated this line to set the prediction object
      } else {
        setIsLoading(false);
        console.error("API returned an error:", result);
      }
    } catch (error) {
      setIsLoading(false);
      console.error("An error occurred:", error);
    }
  };
  

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input
          type="text"
          name="prompt"
          value={inputData.prompt}
          onChange={handleChange}
          placeholder="Enter your prompt"
        />
        <input
          type="number"
          name="width"
          value={inputData.width}
          onChange={handleChange}
        />
        <input
          type="number"
          name="height"
          value={inputData.height}
          onChange={handleChange}
        />
        <input
          type="number"
          name="steps"
          value={inputData.steps}
          onChange={handleChange}
        />
        <input
          type="number"
          name="fps"
          value={inputData.fps}
          onChange={handleChange}
        />
        <input
          type="number"
          name="seed"
          value={inputData.seed || ''}
          onChange={handleChange}
          placeholder="Seed (Optional)"
        />
        <button type="submit">Submit</button>
      </form>

      {isLoading && <div>Processing...</div>}
      
      {output && output.output && (
  <div>
    <h2>Generated Video:</h2>
    <video controls width="500">
      <source src={output.output} type="video/mp4" />
      Your browser does not support the video tag.
    </video>
  </div>
      )}
    </div>
  );
};

export default IndexPage;
