import React, { useState, useEffect } from "react";
import { useGemini } from "../../../hooks/useGemini";
import { useDebounce } from "../../../hooks/useDebounce";
import { useGenerator } from "../../../context/GeneratorContext";
import { getAssetsUrl } from "../../../utils/api";
import {
  ImageCard,
  ImageGrid,
  LoadingSpinner,
  ErrorMessage,
} from "../../shared";

const GEMINI_AVATAR = "imgs/gemini-logo.png";
const PROVIDER_ID = "gemini";

export default function GeminiGenerator() {
  const [query, setQuery] = useState("");
  const [imageCount, setImageCount] = useState(2);
  const [imageSize, setImageSize] = useState("medium");
  const debouncedQuery = useDebounce(query, 500);
  const { setPreviewImageList, setIsGenerating } = useGenerator();
  const {
    generatedImages,
    loading,
    error,
    generateImage,
    clearImages,
  } = useGemini();

  const handleSubmit = (e) => {
    e.preventDefault();
    if (debouncedQuery.trim()) {
      generateImage(debouncedQuery, imageCount, imageSize);
    }
  };

  const assetsUrl = getAssetsUrl();

  // Register images for modal navigation
  useEffect(() => {
    if (generatedImages.length > 0) {
      const list = generatedImages.map((image, idx) => ({
        imageSrc: image.url,
        imageAlt: image.revised_prompt || query || "Generated image",
        previewUrl: image.url,
        author: {
          url: "https://ai.google.dev/",
          avatar: `${assetsUrl}${GEMINI_AVATAR}`,
          name: "Google Gemini",
        },
        importUrl: image.url,
        downloadOptions: [
          { label: "Original", type: "original", url: image.url },
        ],
        providerId: PROVIDER_ID,
        imageId: image.id || `gemini-${idx}`,
        providerBadge: "Gemini",
        index: idx,
      }));
      setPreviewImageList(list);
    }
  }, [generatedImages, query, assetsUrl, setPreviewImageList]);

  // Update generating state
  useEffect(() => {
    setIsGenerating(loading);
  }, [loading, setIsGenerating]);

  return (
    <div>
      <div className="max-w-2xl mx-auto mb-8">
        <div className="bg-white rounded-xl border border-gray-100 overflow-hidden">
          <div className="p-6 border-b border-gray-100">
            <div className="flex items-center gap-2.5">
              <span className="flex items-center justify-center w-8 h-8 rounded-lg bg-gray-100 text-gray-600" aria-hidden>
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                </svg>
              </span>
              <div>
                <h3 className="text-sm font-semibold text-gray-900">Google Gemini</h3>
                <p className="text-xs text-gray-500">Imagen 4.0 – describe your image and generate</p>
              </div>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="p-4 sm:p-6 space-y-4">
            <div>
              <label htmlFor="gemini-prompt" className="block text-sm font-medium text-gray-700 mb-1.5">
                Describe your image
              </label>
              <textarea
                id="gemini-prompt"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="e.g., A serene mountain landscape at sunset with purple sky"
                disabled={loading}
                rows={3}
                className="w-full py-2.5 px-3 rounded-md border border-gray-200 bg-white text-sm outline-none focus:border-gray-800 focus:ring-1 focus:ring-gray-800/20 resize-none disabled:bg-gray-50 disabled:cursor-not-allowed transition-colors"
                aria-label="Image prompt"
              />
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <div>
                <label htmlFor="image-count" className="block text-sm font-medium text-gray-700 mb-1.5">
                  Count
                </label>
                <select
                  id="image-count"
                  value={imageCount}
                  onChange={(e) => setImageCount(Number(e.target.value))}
                  disabled={loading}
                  className="w-full h-9 px-3 rounded-md border border-gray-200 bg-white text-sm outline-none focus:border-gray-800 focus:ring-1 focus:ring-gray-800/20 transition-colors disabled:bg-gray-50 disabled:cursor-not-allowed"
                >
                  <option value={1}>1 Image</option>
                  <option value={2}>2 Images</option>
                  <option value={3}>3 Images</option>
                  <option value={4}>4 Images</option>
                </select>
              </div>

              <div>
                <label htmlFor="image-size" className="block text-sm font-medium text-gray-700 mb-1.5">
                  Size
                </label>
                <select
                  id="image-size"
                  value={imageSize}
                  onChange={(e) => setImageSize(e.target.value)}
                  disabled={loading}
                  className="w-full h-9 px-3 rounded-md border border-gray-200 bg-white text-sm outline-none focus:border-gray-800 focus:ring-1 focus:ring-gray-800/20 transition-colors disabled:bg-gray-50 disabled:cursor-not-allowed"
                >
                  <option value="small">512×512</option>
                  <option value="medium">1024×1024</option>
                  <option value="large">2048×2048</option>
                </select>
              </div>

              <div className="flex items-end">
                <button
                  type="submit"
                  disabled={loading || !query.trim()}
                  className="w-full h-9 rounded-md border border-gray-800 bg-gray-800 text-sm font-medium text-white hover:bg-gray-900 focus:outline-none focus:ring-2 focus:ring-gray-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
                >
                  {loading ? (
                    <>
                      <svg className="animate-spin h-4 w-4" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                        <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" />
                      </svg>
                      <span>Generating...</span>
                    </>
                  ) : (
                    <>
                      <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                        <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                      </svg>
                      <span>Generate</span>
                    </>
                  )}
                </button>
              </div>
            </div>

            <div className="p-3 rounded-md bg-gray-50 border border-gray-100 flex items-start gap-2">
              <svg className="w-3.5 h-3.5 text-gray-400 mt-0.5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <p className="text-xs text-gray-600 leading-relaxed">
                <span className="font-medium text-gray-700">Tip:</span> Add details like style, mood, lighting, and composition for better results.
              </p>
            </div>
          </form>
        </div>
      </div>

      <ErrorMessage message={error} onDismiss={clearImages} />

      {loading ? (
        <div className="flex flex-col items-center justify-center py-16">
          <div className="relative">
            <div className="w-20 h-20 border-4 border-indigo-200 border-t-gray-800 rounded-full animate-spin" />
            <div className="absolute inset-0 flex items-center justify-center">
              <svg className="w-8 h-8 text-gray-800" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
            </div>
          </div>
          <p className="mt-4 text-gray-600 font-medium">Generating your images with Gemini...</p>
          <p className="mt-2 text-sm text-gray-500">This may take a few moments</p>
        </div>
      ) : generatedImages.length > 0 ? (
        <>
          <div className="mb-4 flex items-center justify-between">
            <h3 className="text-lg font-semibold text-gray-900">Generated Images ({generatedImages.length})</h3>
            <button
              onClick={clearImages}
              className="text-sm text-gray-600 hover:text-gray-900 font-medium"
            >
              Clear All
            </button>
          </div>
          <ImageGrid>
            {generatedImages.map((image, index) => (
              <ImageCard
                key={image.id || index}
                index={index}
                providerId="gemini"
                imageId={image.id || `gemini-${index}`}
                imageSrc={image.url}
                imageAlt={image.revised_prompt || query || "Generated image"}
                previewUrl={image.url}
                author={{
                  url: "https://ai.google.dev/",
                  avatar: `${assetsUrl}${GEMINI_AVATAR}`,
                  name: "Google Gemini",
                }}
                importUrl={image.url}
                downloadOptions={[
                  { label: "Original", type: "original", url: image.url },
                ]}
                providerBadge="Gemini"
              />
            ))}
          </ImageGrid>
        </>
      ) : null}
    </div>
  );
}
