import React, { useState } from "react";
import { searchGrounding } from "../services/gemini";
import { GroundingSource } from "../services/types";
import { useTranslation } from "react-i18next";

const SearchView: React.FC = () => {
  const [query, setQuery] = useState("");
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState<{
    text: string;
    sources: GroundingSource[];
  } | null>(null);
  const { t } = useTranslation();

  const handleSearch = async () => {
    if (!query.trim() || loading) return;
    setLoading(true);
    setResult(null);
    try {
      const data = await searchGrounding(query);
      setResult(data);
    } catch (error) {
      console.error(error);
      alert("Search failed. Try a different query.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col h-full bg-gray-950">
      <div className="p-12 max-w-4xl mx-auto w-full">
        <div className="text-center mb-12">
          <h2 className="text-4xl font-extrabold mb-4 bg-gradient-to-r from-blue-400 to-emerald-400 bg-clip-text text-transparent">
            {t("insightEngine")}
          </h2>
          <p className="text-gray-400 text-lg">
            {t("realTimeWebSearchPoweredByGoogleGrounding")}
          </p>
        </div>

        <div className="relative group">
          <input
            type="text"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSearch()}
            placeholder="What are the major highlights of the tech industry today?"
            className="w-full bg-gray-900/50 text-xl text-gray-100 rounded-3xl px-8 py-6 focus:outline-none focus:ring-4 focus:ring-blue-500/20 border-2 border-gray-800 group-hover:border-gray-700 transition-all placeholder-gray-700 shadow-2xl"
          />
          <button
            onClick={handleSearch}
            disabled={loading}
            className="absolute right-4 top-4 bottom-4 bg-blue-600 hover:bg-blue-500 disabled:bg-gray-800 text-white rounded-2xl px-8 font-bold transition-colors shadow-lg"
          >
            {loading ? "Thinking..." : "Search"}
          </button>
        </div>

        {loading && (
          <div className="mt-20 flex flex-col items-center space-y-4">
            <div className="flex space-x-2">
              <div className="w-3 h-3 bg-blue-500 rounded-full animate-ping"></div>
              <div className="w-3 h-3 bg-blue-500 rounded-full animate-ping [animation-delay:0.2s]"></div>
              <div className="w-3 h-3 bg-blue-500 rounded-full animate-ping [animation-delay:0.4s]"></div>
            </div>
            <p className="text-gray-500 animate-pulse font-medium">
              {t("scouringTheWebForRealTimeInformation")}
            </p>
          </div>
        )}

        {result && (
          <div className="mt-12 space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
            <div className="bg-gray-900/80 border border-gray-800 p-8 rounded-3xl shadow-xl leading-relaxed text-gray-200">
              <div className="prose prose-invert max-w-none">
                <p className="whitespace-pre-wrap text-lg">{result.text}</p>
              </div>
            </div>

            {result.sources.length > 0 && (
              <div className="space-y-3">
                <h3 className="text-sm font-bold uppercase tracking-widest text-gray-500 px-2">
                  Verified Sources
                </h3>
                <div className="flex flex-wrap gap-3">
                  {result.sources.map((source, i) => (
                    <a
                      key={i}
                      href={source.uri}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="bg-gray-900 border border-gray-800 hover:border-blue-500/50 hover:bg-gray-800 px-4 py-2 rounded-xl text-sm text-gray-300 transition-all flex items-center space-x-2"
                    >
                      <svg
                        className="w-4 h-4 text-blue-400"
                        fill="none"
                        stroke="currentColor"
                        viewBox="0 0 24 24"
                      >
                        <path
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          strokeWidth={2}
                          d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                        />
                      </svg>
                      <span className="font-medium">{source.title}</span>
                    </a>
                  ))}
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default SearchView;
