"use client";

import { useState, useRef, useEffect } from "react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Upload, Loader2 } from "lucide-react";
import { toast } from "sonner";
import Image from "next/image";

interface AvatarUploadProps {
  currentImage?: string | null;
  userName?: string | null;
  onUploadComplete?: (imageUrl: string) => void;
}

export default function AvatarUpload({
  currentImage,
  userName,
  onUploadComplete,
}: AvatarUploadProps) {
  const [isUploading, setIsUploading] = useState(false);
  const [preview, setPreview] = useState<string | null>(null);
  const [signedUrl, setSignedUrl] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Fetch signed URL for S3 images
  useEffect(() => {
    if (!currentImage || preview) return;

    // If it's a local path or full URL, use it directly
    if (currentImage.startsWith('/') || currentImage.startsWith('http')) {
      setSignedUrl(currentImage);
      return;
    }

    // If it's an S3 key, fetch signed URL
    if (currentImage.startsWith('avatars/')) {
      const fetchSignedUrl = async () => {
        try {
          const response = await fetch(
            `/api/images/signed-url?key=${encodeURIComponent(currentImage)}`
          );
          
          if (response.ok) {
            const data = await response.json();
            setSignedUrl(data.url);
          }
        } catch (error) {
          console.error('Error fetching signed URL:', error);
        }
      };

      fetchSignedUrl();
    }
  }, [currentImage, preview]);

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Validate file type
    const allowedTypes = ["image/jpeg", "image/png", "image/webp"];
    if (!allowedTypes.includes(file.type)) {
      toast.error("Invalid file type. Please upload a JPG, PNG, or WebP image.");
      return;
    }

    // Validate file size (2MB)
    if (file.size > 2 * 1024 * 1024) {
      toast.error("File too large. Please upload an image smaller than 2MB.");
      return;
    }

    // Show preview
    const reader = new FileReader();
    reader.onloadend = () => {
      setPreview(reader.result as string);
    };
    reader.readAsDataURL(file);

    // Upload file
    setIsUploading(true);
    try {
      const formData = new FormData();
      formData.append("avatar", file);

      const response = await fetch("/api/users/me/avatar", {
        method: "POST",
        body: formData,
      });

      if (!response.ok) {
        const error = await response.json();
        throw new Error(error.error || "Failed to upload avatar");
      }

      const data = await response.json();
      toast.success("Avatar uploaded successfully!");

      if (onUploadComplete && data.user.image) {
        onUploadComplete(data.user.image);
      }

      // Set the signed URL from response
      if (data.user.imageUrl) {
        setSignedUrl(data.user.imageUrl);
      }

      // Clear preview after successful upload
      setTimeout(() => setPreview(null), 500);
    } catch (error) {
      console.error("Upload error:", error);
      toast.error(error instanceof Error ? error.message : "Failed to upload avatar");
      setPreview(null);
    } finally {
      setIsUploading(false);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  const displayImage = preview || signedUrl;
  const initials = userName?.charAt(0).toUpperCase() || "U";

  return (
    <div className="flex flex-col items-center gap-4">
      <div className="relative">
        <Avatar className="h-24 w-24">
          {displayImage ? (
            <Image 
              src={displayImage} 
              alt={userName || "User"} 
              width={96}
              height={96}
              quality={95}
              priority
              className="rounded-full object-cover"
            />
          ) : (
            <AvatarFallback className="text-2xl">{initials}</AvatarFallback>
          )}
        </Avatar>
        {isUploading && (
          <div className="absolute inset-0 flex items-center justify-center bg-black/50 rounded-full">
            <Loader2 className="h-8 w-8 text-white animate-spin" />
          </div>
        )}
      </div>

      <input
        ref={fileInputRef}
        type="file"
        accept="image/jpeg,image/png,image/webp"
        onChange={handleFileSelect}
        className="hidden"
        disabled={isUploading}
      />

      <Button
        type="button"
        variant="outline"
        size="sm"
        onClick={() => fileInputRef.current?.click()}
        disabled={isUploading}
      >
        <Upload className="h-4 w-4 mr-2" />
        {isUploading ? "Uploading..." : "Change Avatar"}
      </Button>

      <p className="text-xs text-muted-foreground text-center">
        JPG, PNG or WebP. Max 2MB.
      </p>
    </div>
  );
}
