import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { addToQueue } from "../api/queue";
import { getQuality } from "../components/Navbar";

interface Video {
  id: string;
  videoId: string;
  title: string;
  description: string;
  thumbnail: string;
  url: string;
  category: string;
  duration: string;
  views: string;
  channel: string;
  isShort?: boolean;
  published: string;
}

export default function SearchResults() {
  const [video, setVideo] = useState<Video | null>(null);
  const [_, setSearchResults] = useState<Video[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();

  useEffect(() => {
    const storedResults = sessionStorage.getItem("searchResults");
    const storedVideo = sessionStorage.getItem("currentVideo");

    if (storedResults && storedVideo) {
      try {
        const results: Video[] = JSON.parse(storedResults);
        const currentVideo: Video = JSON.parse(storedVideo);

        setSearchResults(results);
        setVideo(currentVideo);
        setIsLoading(false);
      } catch (err) {
        console.error("Failed to parse session storage:", err);
        setError("Failed to load video details.");
        setIsLoading(false);
      }
    } else {
      setError("No video selected. Please search for videos first.");
      setIsLoading(false);
    }
  }, []);

  const handleDownload = async () => {
    if (!video) return;

    setIsLoading(true);
    try {
      const selectedCategory =
        (document.getElementById("downloadCategory") as HTMLSelectElement)
          ?.value || video.category || "General";
      await addToQueue({
        videoId: video.videoId,
        title: video.title,
        thumbnail: video.thumbnail,
        category: selectedCategory,
        url: video.url,
        quality: getQuality(),
      });
      alert("Video added to download queue!");
      navigate("/queue");
    } catch (err) {
      console.error("Failed to download video:", err);
      setError("Failed to add video to queue. Please try again.");
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-red-600"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="max-w-4xl mx-auto">
        <div className="bg-red-500/10 border border-red-500/50 text-red-500 p-4 rounded-lg text-center mt-8">
          {error}
        </div>
        <button
          onClick={() => navigate("/")}
          className="mt-4 px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors"
        >
          Go Back to Search
        </button>
      </div>
    );
  }

  if (!video) {
    return null;
  }

  return (
    <div className="max-w-6xl mx-auto">
      <button
        onClick={() => navigate("/")}
        className="mb-6 flex items-center text-slate-400 hover:text-white transition-colors"
      >
        <svg
          className="w-4 h-4 mr-2"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            strokeWidth={2}
            d="M15 19l-7-7 7-7"
          />
        </svg>
        Back to Search
      </button>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2">
          <div className="bg-slate-800 rounded-xl overflow-hidden shadow-2xl">
            <div className="aspect-video bg-black">
              <img
                src={video.thumbnail}
                alt={video.title}
                className="w-full h-full object-cover"
              />
            </div>
            <div className="p-6">
              <h1 className="text-2xl md:text-3xl font-bold text-white mb-4 line-clamp-2">
                {video.title}
              </h1>
              <div className="flex flex-wrap items-center gap-4 text-sm text-slate-400 mb-4">
                <span className="flex items-center">
                  <svg
                    className="w-5 h-5 mr-2 text-red-600"
                    fill="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.376.545a3.017 3.017 0 0 0-2.122 2.136C1.997 8.268 1.997 12 1.997 12s0 3.732 1.997 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.545 9.376.545 9.376.545s7.505 0 9.376-.545a3.015 3.015 0 0 0 2.122-2.136c1.997-2.082 1.997-5.814 1.997-5.814s0-3.732-1.997-5.814zM9.525 12.428V7.75l9.147 4.678-9.147 4.678V12.428c0-1.546-1.235-2.8-2.76-2.8-1.526 0-2.76 1.254-2.76 2.8s1.235 2.8 2.76 2.8c1.525 0 2.76-1.254 2.76-2.8" />
                  </svg>
                  {video.views}
                </span>
                <span>{video.published}</span>
                {video.isShort && (
                  <span className="inline-block bg-red-600 text-white text-[10px] px-1.5 py-0.5 rounded">
                    SHORT
                  </span>
                )}
              </div>
              <div className="mb-4">
                <h3 className="text-sm font-semibold text-slate-400 mb-2">
                  Channel
                </h3>
                <div className="flex items-center gap-3">
                  <div className="w-10 h-10 bg-slate-700 rounded-full flex items-center justify-center text-white">
                    {video.channel.charAt(0).toUpperCase()}
                  </div>
                  <span className="text-white">{video.channel}</span>
                </div>
              </div>
              <div className="mb-4">
                <h3 className="text-sm font-semibold text-slate-400 mb-2">
                  Description
                </h3>
                <p className="text-slate-300 text-sm line-clamp-3">
                  {video.description}
                </p>
              </div>
            </div>
          </div>
        </div>

        <div className="lg:col-span-1">
          <div className="bg-slate-800 rounded-xl p-6 shadow-xl">
            <h2 className="text-xl font-bold text-white mb-4">
              Download Options
            </h2>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-slate-400 mb-2">
                  Category
                </label>
                <select
                  id="downloadCategory"
                  defaultValue={video.category || "General"}
                  className="w-full px-4 py-2 bg-slate-900 border border-slate-700 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-red-600"
                >
                  <option value="General">General</option>
                  <option value="Music">Music</option>
                  <option value="Videos">Videos</option>
                  <option value="Podcasts">Podcasts</option>
                  <option value="Educational">Educational</option>
                  <option value="Gaming">Gaming</option>
                </select>
              </div>
              <button
                onClick={handleDownload}
                disabled={isLoading}
                className="w-full py-3 px-4 bg-red-600 text-white rounded-lg font-semibold hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {isLoading ? (
                  <>
                    <svg
                      className="animate-spin h-5 w-5"
                      xmlns="http://www.w3.org/2000/svg"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      ></circle>
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                      ></path>
                    </svg>
                    Downloading...
                  </>
                ) : (
                  <>
                    <svg
                      className="w-5 h-5"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"
                      />
                    </svg>
                    Download Now
                  </>
                )}
              </button>
              <button
                onClick={() => navigate("/queue")}
                className="w-full py-2 px-4 bg-slate-700 text-slate-300 rounded-lg font-medium hover:bg-slate-600 transition-colors"
              >
                View Queue
              </button>
            </div>
          </div>

          <div className="bg-slate-800 rounded-xl p-6 mt-6">
            <h3 className="text-sm font-semibold text-slate-400 mb-3">
              Video Details
            </h3>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-slate-500">Duration:</span>
                <span className="text-white">{video.duration}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-500">Views:</span>
                <span className="text-white">{video.views}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-500">Category:</span>
                <span className="text-white">
                  {video.category || "General"}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-slate-500">Source:</span>
                <a
                  href={video.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-red-600 hover:underline"
                >
                  YouTube
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
