'use client';

import { useState } from 'react';
import Image from 'next/image';

export interface UploadResult {
  id: string;
  timestamp: Date;
  originalFile: {
    name: string;
    size: number;
    type: string;
  };
  uploadedImage: {
    url: string;
    width?: number;
    height?: number;
    size?: number;
  };
  durationMs?: number;
}

export interface UploadResultCardProps {
  result: UploadResult;
  onZoom: (url: string) => void;
  onDownload: (url: string, filename: string) => void;
}

export function UploadResultCard({ result, onZoom, onDownload }: UploadResultCardProps) {
  const [urlCopied, setUrlCopied] = useState(false);
  const [detailsExpanded, setDetailsExpanded] = useState(false);

  // Copy URL to clipboard
  const copyUrl = () => {
    navigator.clipboard.writeText(result.uploadedImage.url);
    setUrlCopied(true);
    setTimeout(() => setUrlCopied(false), 2000);
  };

  // Format file size
  const formatFileSize = (bytes: number): string => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
  };

  // Format duration
  const formatDuration = (ms: number): string => {
    if (ms < 1000) return `${ms}ms`;
    return `${(ms / 1000).toFixed(2)}s`;
  };

  return (
    <div className="p-5 bg-slate-900/80 backdrop-blur-sm border border-slate-700 rounded-2xl animate-fade-in">
      {/* Header */}
      <div className="mb-4 flex items-center justify-between gap-3 flex-wrap">
        <div className="flex items-center gap-3">
          <span className="text-sm text-gray-500">{result.timestamp.toLocaleString()}</span>
          {result.durationMs && (
            <span className="px-3 py-1 text-xs font-medium bg-green-600/20 text-green-400 rounded-full border border-green-600/30">
              {formatDuration(result.durationMs)}
            </span>
          )}
        </div>

        {/* Action buttons */}
        <div className="flex gap-2">
          <button
            onClick={() => setDetailsExpanded(!detailsExpanded)}
            className="px-3 py-1.5 text-xs font-medium bg-slate-800 hover:bg-slate-700 text-gray-300 hover:text-white rounded-lg transition-colors border border-slate-700 focus:ring-2 focus:ring-amber-500"
            aria-expanded={detailsExpanded}
            aria-label={detailsExpanded ? 'Hide details' : 'View details'}
          >
            {detailsExpanded ? 'Hide Details' : 'View Details'}
          </button>
        </div>
      </div>

      {/* Main content - Image and metadata */}
      <div className="flex flex-col lg:flex-row gap-6">
        {/* Image preview */}
        <div className="flex-shrink-0">
          <div className="relative group">
            <div className="relative w-full lg:w-80 h-80 rounded-lg overflow-hidden border border-slate-700 bg-slate-950 cursor-pointer">
              <Image
                src={result.uploadedImage.url}
                alt={result.originalFile.name}
                fill
                className="object-contain hover:scale-105 transition-transform duration-300"
                onClick={() => onZoom(result.uploadedImage.url)}
                sizes="(max-width: 1024px) 100vw, 320px"
              />
            </div>

            {/* Hover overlay with download button */}
            <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg flex items-center justify-center">
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onDownload(result.uploadedImage.url, result.originalFile.name);
                }}
                className="px-4 py-2 bg-amber-600 hover:bg-amber-700 text-white text-sm font-semibold rounded-lg transition-colors shadow-lg focus:ring-2 focus:ring-amber-500"
                aria-label="Download image"
              >
                Download
              </button>
            </div>
          </div>

          {/* Click to zoom hint */}
          <p className="mt-2 text-xs text-gray-500 text-center">Click to view full size</p>
        </div>

        {/* Metadata */}
        <div className="flex-1 min-w-0">
          {/* File name */}
          <h3 className="text-lg font-semibold text-white mb-3 truncate" title={result.originalFile.name}>
            {result.originalFile.name}
          </h3>

          {/* Badges */}
          <div className="flex flex-wrap gap-2 mb-4">
            <span className="px-3 py-1.5 text-xs font-medium bg-slate-700/50 text-gray-300 rounded-full border border-slate-600">
              {formatFileSize(result.originalFile.size)}
            </span>
            <span className="px-3 py-1.5 text-xs font-medium bg-amber-600/20 text-amber-400 rounded-full border border-amber-600/30">
              {result.originalFile.type.split('/')[1].toUpperCase()}
            </span>
            {result.uploadedImage.width && result.uploadedImage.height && (
              <span className="px-3 py-1.5 text-xs font-medium bg-purple-600/20 text-purple-400 rounded-full border border-purple-600/30">
                {result.uploadedImage.width} × {result.uploadedImage.height}
              </span>
            )}
          </div>

          {/* URL with copy button */}
          <div className="mb-4">
            <label className="block text-xs font-medium text-gray-400 mb-2">
              Image URL
            </label>
            <div className="flex items-center gap-2">
              <div className="flex-1 px-3 py-2 bg-slate-800 border border-slate-700 rounded-lg text-sm text-gray-300 font-mono truncate">
                {result.uploadedImage.url}
              </div>
              <button
                onClick={copyUrl}
                className="px-4 py-2 bg-slate-800 hover:bg-slate-700 border border-slate-700 rounded-lg text-sm text-gray-300 hover:text-white transition-colors whitespace-nowrap focus:ring-2 focus:ring-amber-500"
                aria-label="Copy image URL"
              >
                {urlCopied ? '✓ Copied' : 'Copy URL'}
              </button>
            </div>
          </div>

          {/* Action buttons */}
          <div className="flex flex-wrap gap-3">
            <button
              onClick={() => onZoom(result.uploadedImage.url)}
              className="px-4 py-2 bg-gradient-to-r from-purple-600 to-cyan-600 hover:from-purple-500 hover:to-cyan-500 text-white text-sm font-semibold rounded-lg transition-all shadow-lg focus:ring-2 focus:ring-purple-500"
              aria-label="View full size"
            >
              View Full Size
            </button>
            <button
              onClick={() => onDownload(result.uploadedImage.url, result.originalFile.name)}
              className="px-4 py-2 bg-slate-800 hover:bg-slate-700 border border-slate-700 text-white text-sm font-semibold rounded-lg transition-colors focus:ring-2 focus:ring-amber-500"
              aria-label="Download image"
            >
              Download
            </button>
          </div>
        </div>
      </div>

      {/* Expanded details */}
      {detailsExpanded && (
        <div className="mt-5 pt-5 border-t border-slate-700/50 animate-fade-in">
          <h4 className="text-sm font-semibold text-white mb-3">Upload Details</h4>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
            {/* Left column */}
            <div className="space-y-2">
              <div className="flex justify-between">
                <span className="text-gray-400">Original Filename:</span>
                <span className="text-gray-300 font-mono text-xs truncate ml-2 max-w-[200px]" title={result.originalFile.name}>
                  {result.originalFile.name}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">File Type:</span>
                <span className="text-gray-300 font-mono">{result.originalFile.type}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">File Size:</span>
                <span className="text-gray-300 font-mono">
                  {formatFileSize(result.originalFile.size)}
                </span>
              </div>
            </div>

            {/* Right column */}
            <div className="space-y-2">
              {result.uploadedImage.width && result.uploadedImage.height && (
                <div className="flex justify-between">
                  <span className="text-gray-400">Dimensions:</span>
                  <span className="text-gray-300 font-mono">
                    {result.uploadedImage.width} × {result.uploadedImage.height}
                  </span>
                </div>
              )}
              {result.durationMs && (
                <div className="flex justify-between">
                  <span className="text-gray-400">Upload Duration:</span>
                  <span className="text-gray-300 font-mono">{formatDuration(result.durationMs)}</span>
                </div>
              )}
              <div className="flex justify-between">
                <span className="text-gray-400">Uploaded At:</span>
                <span className="text-gray-300 font-mono text-xs">
                  {result.timestamp.toLocaleTimeString()}
                </span>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
