import React, { useState, useEffect } from "react";
import { generateVideo } from "../services/gemini";
import { GeneratedVideo } from "../services/types";

const VideoView: React.FC = () => {
  const [prompt, setPrompt] = useState("");
  const [loading, setLoading] = useState(false);
  const [history, setHistory] = useState<GeneratedVideo[]>([]);
  const [hasKey, setHasKey] = useState(false);
  const [aspectRatio, setAspectRatio] = useState<"16:9" | "9:16">("16:9");

  useEffect(() => {
    const checkKey = async () => {
      // @ts-ignore
      const ok = await window.aistudio.hasSelectedApiKey();
      setHasKey(ok);
    };
    checkKey();
  }, []);

  const handleSelectKey = async () => {
    // @ts-ignore
    await window.aistudio.openSelectKey();
    setHasKey(true);
  };

  const handleGenerate = async () => {
    if (!prompt.trim() || loading) return;
    setLoading(true);
    try {
      const url = await generateVideo(prompt, aspectRatio);
      setHistory((prev) => [{ url, prompt, timestamp: new Date() }, ...prev]);
    } catch (error) {
      console.error(error);
      alert(
        "Video generation encountered an error. Veo might be busy or key issues."
      );
    } finally {
      setLoading(false);
    }
  };

  if (!hasKey) {
    return (
      <div className="flex flex-col items-center justify-center h-full bg-gray-950 p-12 text-center">
        <div className="w-20 h-20 bg-yellow-500/10 rounded-full flex items-center justify-center mb-6">
          <svg
            className="w-10 h-10 text-yellow-500"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              strokeWidth={2}
              d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"
            />
          </svg>
        </div>
        <h2 className="text-3xl font-bold mb-4">Activation Required</h2>
        <p className="text-gray-400 max-w-md mb-8">
          To access the professional-grade Veo 3.1 video engine, you must select
          an API key from a billing-enabled Google Cloud project.
        </p>
        <div className="flex flex-col space-y-4">
          <button
            onClick={handleSelectKey}
            className="bg-blue-600 hover:bg-blue-500 text-white px-8 py-3 rounded-xl font-bold transition-all shadow-xl"
          >
            Select Paid API Key
          </button>
          <a
            href="https://ai.google.dev/gemini-api/docs/billing"
            target="_blank"
            className="text-sm text-blue-400 hover:underline"
          >
            Learn about billing →
          </a>
        </div>
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full bg-gray-950">
      <div className="p-8 border-b border-gray-900 flex flex-col space-y-4">
        <div className="flex items-center justify-between">
          <h2 className="text-2xl font-bold">Cinematic Video</h2>
          <span className="bg-indigo-500/10 text-indigo-400 text-[10px] uppercase tracking-widest px-2 py-1 rounded font-bold border border-indigo-500/20">
            Veo 3.1 Pro
          </span>
        </div>
        <div className="flex flex-col md:flex-row gap-4">
          <textarea
            rows={2}
            value={prompt}
            onChange={(e) => setPrompt(e.target.value)}
            placeholder="A slow-motion tracking shot of a silver jaguar running through a dark neon forest..."
            className="flex-1 bg-gray-900 text-gray-100 rounded-xl px-5 py-3 focus:outline-none focus:ring-2 focus:ring-blue-500/50 border border-gray-800 resize-none"
          />
          <div className="flex flex-col space-y-2">
            <select
              value={aspectRatio}
              onChange={(e: any) => setAspectRatio(e.target.value)}
              className="bg-gray-900 text-gray-200 border border-gray-800 rounded-xl px-4 py-2 outline-none"
            >
              <option value="16:9">Landscape (16:9)</option>
              <option value="9:16">Portrait (9:16)</option>
            </select>
            <button
              onClick={handleGenerate}
              disabled={loading}
              className="flex-1 bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-500 hover:to-purple-500 disabled:opacity-50 text-white rounded-xl px-8 py-3 font-semibold transition-all shadow-lg"
            >
              {loading ? "Synthesizing..." : "Generate 720p"}
            </button>
          </div>
        </div>
        {loading && (
          <div className="bg-gray-900 border border-gray-800 rounded-xl p-4 animate-pulse flex items-center space-x-4">
            <div className="w-8 h-8 border-4 border-indigo-500 border-t-transparent rounded-full animate-spin"></div>
            <div>
              <p className="text-sm font-medium text-gray-300">
                Wait, magic in progress...
              </p>
              <p className="text-xs text-gray-500">
                Video generation typically takes 2-4 minutes. Do not close this
                tab.
              </p>
            </div>
          </div>
        )}
      </div>

      <div className="flex-1 overflow-y-auto p-8 grid grid-cols-1 xl:grid-cols-2 gap-8">
        {history.map((video, idx) => (
          <div
            key={idx}
            className="bg-gray-900 border border-gray-800 rounded-2xl overflow-hidden shadow-2xl"
          >
            <video
              controls
              src={video.url}
              className="w-full h-auto aspect-video bg-black"
            />
            <div className="p-4">
              <p className="text-sm text-gray-400 font-medium line-clamp-2">
                "{video.prompt}"
              </p>
              <div className="mt-4 flex justify-between items-center">
                <span className="text-xs text-gray-600">
                  {video.timestamp.toLocaleDateString()}
                </span>
                <a
                  href={video.url}
                  download
                  className="text-xs text-blue-400 font-bold hover:underline"
                >
                  Export MP4
                </a>
              </div>
            </div>
          </div>
        ))}
        {history.length === 0 && !loading && (
          <div className="col-span-full h-full flex flex-col items-center justify-center opacity-20 py-20">
            <svg
              className="w-24 h-24"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={1}
                d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z"
              />
            </svg>
            <p className="mt-4 text-xl font-medium">
              Ready to produce professional cinema?
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default VideoView;
