'use client';

import { useEffect, useRef } from 'react';
import { ImageMetadataBar } from '../ImageMetadataBar';
import { useImageDownloadTime } from './useImageDownloadTime';
import { usePageContext } from '@/contexts/page-context';
import { ExpandedImageView } from '../ExpandedImageView';

export interface ImageCardProps {
  imageUrl: string;
  filename: string;
  width?: number;
  height?: number;
  fileSize: number;
  fileType: string;
  timestamp?: Date;
  className?: string;
  measureDownloadTime?: boolean;
  onDownloadMeasured?: (downloadMs: number) => void;
}

export const ImageCard = ({
  imageUrl,
  filename,
  width,
  height,
  fileSize,
  fileType,
  timestamp,
  className = '',
  measureDownloadTime = false,
  onDownloadMeasured,
}: ImageCardProps) => {
  const { openModal } = usePageContext();
  const { downloadTime, isLoading } = useImageDownloadTime(
    measureDownloadTime ? imageUrl : null
  );

  // Track if we've already called onDownloadMeasured to prevent duplicate calls
  const hasCalledCallback = useRef(false);

  useEffect(() => {
    if (downloadTime !== null && onDownloadMeasured && !hasCalledCallback.current) {
      onDownloadMeasured(downloadTime);
      hasCalledCallback.current = true;
    }
  }, [downloadTime, onDownloadMeasured]);

  const handleImageClick = () => {
    openModal(<ExpandedImageView imageUrl={imageUrl} alt={filename} />);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' || e.key === ' ') {
      e.preventDefault();
      handleImageClick();
    }
  };

  const formatTimestamp = (date: Date): string => {
    return date.toLocaleString('en-US', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  return (
    <div
      className={`p-4 bg-slate-900/80 backdrop-blur-sm border border-slate-700 rounded-xl hover:border-slate-600 transition-all h-full ${className}`}
    >
      <div
        className="aspect-video bg-slate-800 rounded-lg mb-3 overflow-hidden cursor-pointer group relative"
        onClick={handleImageClick}
        role="button"
        tabIndex={0}
        aria-label="View full size image"
        onKeyDown={handleKeyDown}
      >
        <img
          src={imageUrl}
          alt={filename}
          className="w-full h-full object-cover transition-transform group-hover:scale-105"
        />

        <div className="absolute inset-0 bg-gradient-to-b from-black/70 via-transparent to-black/70 opacity-0 group-hover:opacity-100 transition-opacity">
          {timestamp && (
            <div className="absolute top-3 left-3">
              <span className="px-2.5 py-1 bg-black/50 backdrop-blur-sm text-white text-xs font-medium rounded border border-white/10">
                {formatTimestamp(timestamp)}
              </span>
            </div>
          )}

          <div className="absolute top-3 right-3 max-w-[60%]">
            <span
              className="px-2.5 py-1 bg-black/50 backdrop-blur-sm text-white text-xs font-medium rounded border border-white/10 truncate block"
              title={filename}
            >
              {filename}
            </span>
          </div>

          <div className="absolute inset-0 flex items-center justify-center">
            <svg
              className="w-12 h-12 text-white"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"
              />
            </svg>
          </div>
        </div>
      </div>

      {width && height && (
        <ImageMetadataBar
          width={width}
          height={height}
          fileSize={fileSize}
          fileType={fileType}
          showVisualIndicator={true}
          downloadMs={downloadTime}
        />
      )}
    </div>
  );
};
