'use client';

import { useState, useEffect, useCallback } from 'react';
import { useApiKey } from '@/components/shared/ApiKeyWidget/apikey-context';
import { Section } from '@/components/shared/Section';
import { ImageGrid } from '@/components/demo/gallery/ImageGrid';
import { EmptyGalleryState } from '@/components/demo/gallery/EmptyGalleryState';

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
const IMAGES_PER_PAGE = 30;

type ImageItem = {
  name: string;
  url: string;
  size: number;
  contentType: string;
  lastModified: string;
};

type ImagesResponse = {
  success: boolean;
  data?: {
    images: ImageItem[];
    total: number;
    offset: number;
    limit: number;
    hasMore: boolean;
  };
  error?: string;
  message?: string;
};

type DownloadTimeMap = {
  [imageId: string]: number;
};

export default function GalleryPage() {
  // API Key from context
  const { apiKey, apiKeyValidated, focus } = useApiKey();

  const [images, setImages] = useState<ImageItem[]>([]);
  const [offset, setOffset] = useState(0);
  const [hasMore, setHasMore] = useState(false);
  const [loading, setLoading] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [error, setError] = useState('');

  const [downloadTimes, setDownloadTimes] = useState<DownloadTimeMap>({});

  useEffect(() => {
    if (apiKeyValidated) {
      fetchImages(apiKey, 0);
    }
  }, [apiKeyValidated]);

  const fetchImages = async (keyToUse: string, fetchOffset: number) => {
    if (fetchOffset === 0) {
      setLoading(true);
    } else {
      setLoadingMore(true);
    }
    setError('');

    try {
      const response = await fetch(
        `${API_BASE_URL}/api/images/generated?limit=${IMAGES_PER_PAGE}&offset=${fetchOffset}`,
        {
          headers: {
            'X-API-Key': keyToUse,
          },
        }
      );

      if (!response.ok) {
        const errorData: ImagesResponse = await response.json();
        throw new Error(errorData.error || errorData.message || 'Failed to fetch images');
      }

      const result: ImagesResponse = await response.json();

      if (result.success && result.data) {
        const { images: newImages, offset: newOffset, hasMore: newHasMore } = result.data;

        if (fetchOffset === 0) {
          setImages(newImages);
        } else {
          setImages((prev) => [...prev, ...newImages]);
        }
        setOffset(newOffset);
        setHasMore(newHasMore);
      } else {
        throw new Error(result.error || 'Failed to fetch images');
      }
    } catch (error) {
      setError(error instanceof Error ? error.message : 'Failed to load images');
    } finally {
      setLoading(false);
      setLoadingMore(false);
    }
  };

  const handleLoadMore = () => {
    const newOffset = offset + IMAGES_PER_PAGE;
    fetchImages(apiKey, newOffset);
  };

  const handleDownloadMeasured = useCallback((imageId: string, downloadMs: number) => {
    setDownloadTimes((prev) => ({
      ...prev,
      [imageId]: downloadMs,
    }));
  }, []);

  return (
    <Section className="py-12 md:py-16 min-h-screen">
      <header className="mb-8 md:mb-12">
        <h1 className="text-3xl md:text-4xl lg:text-5xl font-bold text-white mb-3">
          Image Gallery
        </h1>
        <p className="text-gray-400 text-base md:text-lg">
          Browse your AI-generated images
        </p>
      </header>

      {/* API Key Required Notice - Only show when not validated */}
      {!apiKeyValidated && (
        <div className="mb-6 p-5 bg-amber-900/10 border border-amber-700/50 rounded-2xl">
          <div className="flex items-center justify-between flex-wrap gap-4">
            <div>
              <h3 className="text-lg font-semibold text-white mb-1">API Key Required</h3>
              <p className="text-sm text-gray-400">Enter your API key to browse your images</p>
            </div>
            <button
              onClick={focus}
              className="px-5 py-2.5 bg-amber-600 hover:bg-amber-700 text-white font-medium rounded-lg transition-colors"
            >
              Enter API Key
            </button>
          </div>
        </div>
      )}

      {apiKeyValidated && (
        <section aria-label="Image Gallery">
          {loading ? (
            <div className="flex flex-col items-center justify-center py-16" role="status" aria-live="polite">
              <div className="animate-spin w-12 h-12 border-4 border-amber-600 border-t-transparent rounded-full mb-4" aria-hidden="true"></div>
              <p className="text-gray-400">Loading images...</p>
            </div>
          ) : error ? (
            <div className="p-6 bg-red-900/20 border border-red-700/50 rounded-2xl" role="alert" aria-live="assertive">
              <p className="text-red-400 font-medium mb-2">{error}</p>
              <p className="text-sm text-red-300/80">
                {error.includes('fetch') || error.includes('load')
                  ? 'Unable to load images. Please check your connection and try refreshing the page.'
                  : 'An error occurred while fetching your images. Please try again later.'}
              </p>
            </div>
          ) : images.length === 0 ? (
            <EmptyGalleryState />
          ) : (
            <>
              <ImageGrid
                images={images}
                onDownloadMeasured={handleDownloadMeasured}
              />

              {hasMore && (
                <div className="flex justify-center mt-8">
                  <button
                    onClick={handleLoadMore}
                    disabled={loadingMore}
                    className="px-8 py-4 rounded-xl bg-gradient-to-r from-amber-600 to-orange-600 text-white font-semibold hover:from-amber-500 hover:to-orange-500 transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-lg shadow-amber-900/30 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:ring-offset-2 focus:ring-offset-slate-950 min-h-[44px]"
                    aria-busy={loadingMore}
                    aria-live="polite"
                  >
                    {loadingMore ? (
                      <span className="flex items-center gap-2">
                        <div className="animate-spin w-4 h-4 border-2 border-white border-t-transparent rounded-full" aria-hidden="true"></div>
                        Loading more images...
                      </span>
                    ) : (
                      'Load More Images'
                    )}
                  </button>
                </div>
              )}
            </>
          )}
        </section>
      )}
    </Section>
  );
}
