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

const OPENAI_AVATAR = "imgs/ChatGPT_logo.svg.png";
const PROVIDER_ID = "openai";

export default function OpenAIGenerator() {
  const [query, setQuery] = useState("");
  const debouncedQuery = useDebounce(query, 500);
  const { setPreviewImageList, setIsGenerating } = useGenerator();
  const {
    generatedImages,
    loading,
    error,
    generateImage,
    clearImages,
  } = useOpenAI();

  const handleSubmit = (e) => {
    e.preventDefault();
    generateImage(debouncedQuery, 2, "medium");
  };

  const assetsUrl = getAssetsUrl();

  // Register images for modal navigation
  useEffect(() => {
    if (generatedImages.length > 0) {
      const list = generatedImages.map((image, idx) => ({
        imageSrc: image.url,
        imageAlt: "Generated image",
        previewUrl: image.url,
        author: {
          url: "#",
          avatar: `${assetsUrl}${OPENAI_AVATAR}`,
          name: "OpenAI",
        },
        importUrl: image.url,
        downloadOptions: [
          { label: "Small", type: "small", url: image.url },
          { label: "Medium", type: "medium", url: image.url },
          { label: "Large", type: "large", url: image.url },
        ],
        providerId: PROVIDER_ID,
        imageId: String(idx),
        providerBadge: "OpenAI",
        index: idx,
      }));
      setPreviewImageList(list);
    }
  }, [generatedImages, 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="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z" />
                </svg>
              </span>
              <div>
                <h3 className="text-sm font-semibold text-gray-900">OpenAI GPT Image</h3>
                <p className="text-xs text-gray-500">Describe your image and generate with AI</p>
              </div>
            </div>
          </div>

          <form onSubmit={handleSubmit} className="p-4 sm:p-6 space-y-4">
            <div>
              <label htmlFor="openai-prompt" className="block text-sm font-medium text-gray-700 mb-1.5">
                Describe your image
              </label>
              <textarea
                id="openai-prompt"
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="e.g., A futuristic city with flying cars at night"
                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>

            <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 with GPT Image</span>
                </>
              )}
            </button>

            <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 subject, setting, style, and mood for better results.
              </p>
            </div>
          </form>
        </div>
      </div>

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

      {loading ? (
        <LoadingSpinner message="Generating images..." />
      ) : (
        <ImageGrid>
          {generatedImages.map((image, index) => (
            <ImageCard
              key={index}
              index={index}
              providerId={PROVIDER_ID}
              imageId={String(index)}
              imageSrc={image.url}
              imageAlt="Generated"
              previewUrl={image.url}
              author={{
                url: "#",
                avatar: `${assetsUrl}${OPENAI_AVATAR}`,
                name: "OpenAI",
              }}
              importUrl={image.url}
              downloadOptions={[
                { label: "Small", type: "small", url: image.url },
                { label: "Medium", type: "medium", url: image.url },
                { label: "Large", type: "large", url: image.url },
              ]}
              providerBadge="OpenAI"
            />
          ))}
        </ImageGrid>
      )}
    </div>
  );
}
