"use client";

import { Heart, Download, Loader2, AlertCircle, MessageSquarePlus } from "lucide-react";
import { Id } from "@/convex/_generated/dataModel";
import { useState } from "react";
import { useMutation, useQuery } from "convex/react";
import { api } from "@/convex/_generated/api";

interface ImageAtomCardProps {
  atom: {
    _id: Id<"atoms">;
    type: string;
    status: "pending" | "processing" | "streaming" | "completed" | "failed";
    progress: number;
    likeCount?: number;
    likedBy?: Id<"users">[];
    metadata: {
      prompt?: string;
      width?: number;
      height?: number;
      storageId?: string;
      originalUrl?: string;
      filename?: string;
    };
  };
  currentUserId?: Id<"users">;
  onAttachToMessage?: (atomId: Id<"atoms">) => void;
}

export function ImageAtomCard({ atom, currentUserId, onAttachToMessage }: ImageAtomCardProps) {
  const toggleLike = useMutation(api.atoms.toggleLike);

  // Get the image URL from Convex storage
  const imageUrl = useQuery(
    api.atoms.getImageUrl,
    atom.metadata.storageId ? { storageId: atom.metadata.storageId } : "skip"
  );

  const [isLiked, setIsLiked] = useState(
    currentUserId ? atom.likedBy?.includes(currentUserId) : false
  );
  const [likeCount, setLikeCount] = useState(atom.likeCount ?? 0);

  const metadata = atom.metadata;
  const isCompleted = atom.status === "completed";
  const isGenerating = ["pending", "processing"].includes(atom.status);
  const hasFailed = atom.status === "failed";

  const handleLike = async () => {
    try {
      const result = await toggleLike({ atomId: atom._id as Id<"atoms"> });
      setIsLiked(result.liked);
      setLikeCount(result.likeCount);
    } catch (error) {
      console.error("Failed to toggle like:", error);
    }
  };

  const handleDownload = async () => {
    if (!imageUrl) return;

    try {
      const response = await fetch(imageUrl);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `image-${atom._id}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (error) {
      console.error("Failed to download image:", error);
    }
  };

  return (
    <div className="image-atom-card rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 overflow-hidden hover:shadow-lg transition-shadow max-w-[600px] max-h-[600px]">
      {/* Image Display */}
      <div className="image-container relative w-full aspect-square bg-gray-100 dark:bg-gray-700">
        {isCompleted && imageUrl ? (
          <img
            src={imageUrl}
            alt={metadata.prompt || "Generated image"}
            className="w-full h-full object-contain max-w-[600px] max-h-[600px]"
          />
        ) : (
          <div className="w-full h-full flex flex-col items-center justify-center">
            {isGenerating && (
              <>
                <Loader2 className="w-12 h-12 animate-spin text-gray-400 mb-2" />
                <div className="text-sm text-gray-500 dark:text-gray-400">
                  {atom.status === "pending" && "⏳ Queued..."}
                  {atom.status === "processing" && "🎨 Generating..."}
                </div>
                {/* Progress Bar */}
                <div className="w-3/4 h-2 bg-gray-200 dark:bg-gray-600 rounded-full mt-3 overflow-hidden">
                  <div
                    className="h-full bg-blue-500 transition-all duration-300"
                    style={{ width: `${atom.progress}%` }}
                  />
                </div>
              </>
            )}
            {hasFailed && (
              <>
                <AlertCircle className="w-12 h-12 text-red-500 mb-2" />
                <div className="text-sm text-red-600 dark:text-red-400">
                  Generation failed
                </div>
              </>
            )}
          </div>
        )}
      </div>

      {/* Info and Actions */}
      <div className="image-info p-3">
        {/* Prompt */}
        {metadata.prompt && (
          <div className="prompt-text text-sm text-gray-700 dark:text-gray-300 mb-3 line-clamp-2">
            {metadata.prompt}
          </div>
        )}

        {/* Actions */}
        <div className="actions flex items-center justify-between">
          {/* Like Button */}
          <div className="flex items-center gap-2">
            <button
              className={`like-button p-2 rounded-full transition-colors ${
                isLiked
                  ? "text-red-500 hover:text-red-600"
                  : "text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300"
              }`}
              onClick={handleLike}
              aria-label={isLiked ? "Unlike" : "Like"}
            >
              <Heart size={18} className={isLiked ? "fill-current" : ""} />
            </button>
            {likeCount > 0 && (
              <span className="text-sm text-gray-600 dark:text-gray-400">
                {likeCount}
              </span>
            )}
          </div>

          <div className="flex items-center gap-2">
            {/* Attach to Message Button */}
            {onAttachToMessage && isCompleted && (
              <button
                className="attach-button p-2 rounded-full transition-colors text-gray-400 hover:text-blue-600 dark:text-gray-500 dark:hover:text-blue-400"
                onClick={() => onAttachToMessage(atom._id)}
                aria-label="Attach to message"
                title="Attach to message"
              >
                <MessageSquarePlus size={18} />
              </button>
            )}

            {/* Download Button */}
            {isCompleted && imageUrl && (
              <button
                className="download-button p-2 rounded-full text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition-colors"
                onClick={handleDownload}
                aria-label="Download image"
              >
                <Download size={18} />
              </button>
            )}
          </div>
        </div>

        {/* Dimensions */}
        {metadata.width && metadata.height && (
          <div className="dimensions text-xs text-gray-500 dark:text-gray-400 mt-2">
            {metadata.width} × {metadata.height}
          </div>
        )}
      </div>
    </div>
  );
}
