import { motion, AnimatePresence } from "motion/react";
import { useState, useRef } from "react";
import { X, Camera, Upload } from "lucide-react";
import { uploadImage } from "../../services/feedService";

interface AvatarSelectionModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSelectAvatar: (avatarUrl: string) => void;
  currentAvatar?: string;
}

// عکس‌های پیشنهادی برای آواتار
const suggestedAvatars = [
  "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=400&q=80",
  "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=400&q=80",
  "https://images.unsplash.com/photo-1527980965255-d3b416303d12?w=400&q=80",
  "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=400&q=80",
  "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&q=80",
  "https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=400&q=80",
  "https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=400&q=80",
  "https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?w=400&q=80",
  "https://images.unsplash.com/photo-1554151228-14d9def656e4?w=400&q=80",
  "https://images.unsplash.com/photo-1522075469751-3a6694fb2f61?w=400&q=80",
  "https://images.unsplash.com/photo-1517841905240-472988babdf9?w=400&q=80",
  "https://images.unsplash.com/photo-1542909168-82c3e7fdca5c?w=400&q=80",
];

export function AvatarSelectionModal({
  isOpen,
  onClose,
  onSelectAvatar,
  currentAvatar,
}: AvatarSelectionModalProps) {
  const [selectedAvatar, setSelectedAvatar] = useState<string | null>(null);
  const [uploadedImage, setUploadedImage] = useState<string | null>(null);
  const [uploadedImageFile, setUploadedImageFile] = useState<File | null>(null);
  const [isUploading, setIsUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setUploadedImageFile(file);
      const reader = new FileReader();
      reader.onloadend = () => {
        const result = reader.result as string;
        setUploadedImage(result);
        setSelectedAvatar(result);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleConfirm = async () => {
    console.log("handleConfirm called");
    console.log("selectedAvatar:", selectedAvatar);
    console.log("uploadedImageFile:", uploadedImageFile);

    if (!selectedAvatar) return;

    setIsUploading(true);

    try {
      let fileToUpload: File | null = uploadedImageFile;

      // اگر عکس پیشنهادی انتخاب شده (URL خارجی)، ابتدا باید دانلود شود
      if (!uploadedImageFile && selectedAvatar.startsWith("http")) {
        console.log("Downloading suggested avatar from URL:", selectedAvatar);

        try {
          const response = await fetch(selectedAvatar);
          const blob = await response.blob();

          // تبدیل blob به File
          const filename = `avatar_${Date.now()}.jpg`;
          fileToUpload = new File([blob], filename, { type: blob.type || "image/jpeg" });

          console.log("Downloaded file:", fileToUpload.name, fileToUpload.size);
        } catch (error) {
          console.error("Error downloading suggested avatar:", error);
          alert("خطا در دانلود تصویر. لطفاً دوباره تلاش کنید.");
          setIsUploading(false);
          return;
        }
      }

      // حالا فایل را به سرور آپلود می‌کنیم
      if (fileToUpload) {
        console.log("Starting image upload...", fileToUpload.name);
        const filename = await uploadImage(fileToUpload, { requireResize: true });
        console.log("Upload result:", filename);

        if (filename) {
          // ارسال نام فایل به والد
          console.log("Sending filename to parent:", filename);
          onSelectAvatar(filename);
          onClose();
        } else {
          console.error("Upload returned null filename");
          alert("خطا در آپلود تصویر. لطفاً دوباره تلاش کنید.");
        }
      } else {
        console.error("No file to upload");
        alert("لطفاً یک تصویر انتخاب کنید.");
      }
    } catch (error) {
      console.error("Error in handleConfirm:", error);
      alert("خطا در آپلود تصویر. لطفاً دوباره تلاش کنید.");
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 z-[100] flex items-center justify-center p-4"
          style={{ backgroundColor: "rgba(0, 0, 0, 0.8)" }}
          onClick={onClose}
        >
          <motion.div
            initial={{ scale: 0.9, y: 20 }}
            animate={{ scale: 1, y: 0 }}
            exit={{ scale: 0.9, y: 20 }}
            onClick={(e) => e.stopPropagation()}
            className="w-full max-w-md rounded-3xl overflow-hidden"
            style={{
              background:
                "linear-gradient(180deg, rgba(32, 76, 106, 0.98) 0%, rgba(20, 40, 60, 0.98) 100%)",
              border: "2px solid rgba(138, 206, 224, 0.3)",
              boxShadow: "0 20px 60px rgba(0, 0, 0, 0.5)",
              maxHeight: "85vh",
            }}
          >
            {/* Header */}
            <div
              className="px-6 py-4 border-b flex items-center justify-between"
              style={{ borderColor: "rgba(138, 206, 224, 0.2)" }}
            >
              <h3
                className="text-lg font-bold"
                style={{
                  color: "#FFFFFF",
                  textShadow: "0 2px 4px rgba(0, 0, 0, 0.3)",
                }}
              >
                انتخاب عکس پروفایل
              </h3>
              <motion.button
                whileTap={{ scale: 0.9 }}
                onClick={onClose}
                className="w-8 h-8 rounded-full flex items-center justify-center"
                style={{
                  background:
                    "linear-gradient(135deg, rgba(239, 68, 68, 0.9) 0%, rgba(220, 38, 38, 0.9) 100%)",
                  boxShadow: "0 2px 8px rgba(239, 68, 68, 0.4)",
                }}
              >
                <X className="w-5 h-5 text-white" />
              </motion.button>
            </div>

            {/* Content */}
            <div
              className="overflow-y-auto p-6"
              style={{ maxHeight: "calc(85vh - 180px)" }}
            >
              {/* آپلود عکس شخصی */}
              <div className="mb-6">
                <h4
                  className="text-sm font-bold mb-3"
                  style={{
                    color: "#8ACEE0",
                    textShadow: "0 1px 2px rgba(0, 0, 0, 0.3)",
                  }}
                >
                  آپلود عکس شخصی
                </h4>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  onChange={handleFileSelect}
                  className="hidden"
                />
                <motion.button
                  whileTap={{ scale: 0.95 }}
                  onClick={() => fileInputRef.current?.click()}
                  className="w-full py-4 rounded-2xl font-bold text-sm flex items-center justify-center gap-2"
                  style={{
                    background:
                      "linear-gradient(135deg, rgba(96, 147, 157, 0.9) 0%, rgba(76, 127, 137, 0.9) 100%)",
                    boxShadow:
                      "0 4px 12px rgba(0, 0, 0, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.1)",
                    border: "2px solid rgba(138, 206, 224, 0.3)",
                    color: "#FFFFFF",
                    textShadow: "0 2px 4px rgba(0, 0, 0, 0.3)",
                  }}
                >
                  <Upload className="w-5 h-5" />
                  <span>انتخاب از گالری</span>
                </motion.button>

                {/* نمایش عکس آپلود شده */}
                {uploadedImage && (
                  <motion.div
                    initial={{ opacity: 0, scale: 0.8 }}
                    animate={{ opacity: 1, scale: 1 }}
                    className="mt-4 flex justify-center"
                  >
                    <div
                      className="w-24 h-24 rounded-full overflow-hidden"
                      style={{
                        border: "3px solid rgba(138, 206, 224, 0.5)",
                        boxShadow:
                          "0 4px 16px rgba(138, 206, 224, 0.4), inset 0 -4px 12px rgba(0, 0, 0, 0.3)",
                      }}
                    >
                      <img
                        src={uploadedImage}
                        alt="آپلود شده"
                        className="w-full h-full object-cover"
                      />
                    </div>
                  </motion.div>
                )}
              </div>

              {/* عکس‌های پیشنهادی */}
              <div>
                <h4
                  className="text-sm font-bold mb-3"
                  style={{
                    color: "#8ACEE0",
                    textShadow: "0 1px 2px rgba(0, 0, 0, 0.3)",
                  }}
                >
                  عکس‌های پیشنهادی
                </h4>
                <div className="grid grid-cols-4 gap-3">
                  {suggestedAvatars.map((avatar, index) => (
                    <motion.button
                      key={index}
                      initial={{ opacity: 0, scale: 0.8 }}
                      animate={{ opacity: 1, scale: 1 }}
                      transition={{ delay: index * 0.05 }}
                      whileTap={{ scale: 0.9 }}
                      onClick={() => {
                        setSelectedAvatar(avatar);
                        setUploadedImage(null);
                        setUploadedImageFile(null);
                      }}
                      className="aspect-square rounded-full overflow-hidden relative"
                      style={{
                        border:
                          selectedAvatar === avatar
                            ? "3px solid rgba(255, 193, 7, 0.8)"
                            : "2px solid rgba(138, 206, 224, 0.3)",
                        boxShadow:
                          selectedAvatar === avatar
                            ? "0 4px 16px rgba(255, 193, 7, 0.6), inset 0 0 20px rgba(255, 193, 7, 0.2)"
                            : "0 2px 8px rgba(0, 0, 0, 0.3)",
                      }}
                    >
                      <img
                        src={avatar}
                        alt={`آواتار ${index + 1}`}
                        className="w-full h-full object-cover"
                      />
                      {selectedAvatar === avatar && (
                        <motion.div
                          initial={{ scale: 0 }}
                          animate={{ scale: 1 }}
                          className="absolute inset-0 flex items-center justify-center"
                          style={{
                            background: "rgba(255, 193, 7, 0.3)",
                          }}
                        >
                          <div
                            className="w-6 h-6 rounded-full flex items-center justify-center"
                            style={{
                              background:
                                "linear-gradient(135deg, rgba(255, 193, 7, 0.95) 0%, rgba(255, 152, 0, 0.95) 100%)",
                              boxShadow: "0 2px 8px rgba(0, 0, 0, 0.4)",
                            }}
                          >
                            <Camera className="w-3 h-3 text-white" />
                          </div>
                        </motion.div>
                      )}
                    </motion.button>
                  ))}
                </div>
              </div>
            </div>

            {/* Footer - Action Buttons */}
            <div
              className="px-6 py-4 border-t flex gap-3"
              style={{ borderColor: "rgba(138, 206, 224, 0.2)" }}
            >
              <motion.button
                whileTap={{ scale: 0.95 }}
                onClick={onClose}
                className="flex-1 py-3 rounded-full font-bold text-white"
                style={{
                  background:
                    "linear-gradient(135deg, rgba(96, 147, 157, 0.6) 0%, rgba(76, 127, 137, 0.6) 100%)",
                  boxShadow: "0 4px 12px rgba(0, 0, 0, 0.3)",
                  border: "1.5px solid rgba(138, 206, 224, 0.3)",
                }}
              >
                انصراف
              </motion.button>
              <motion.button
                whileTap={{ scale: selectedAvatar ? 0.95 : 1 }}
                onClick={handleConfirm}
                disabled={!selectedAvatar || isUploading}
                className="flex-1 py-3 rounded-full font-bold"
                style={{
                  background: selectedAvatar && !isUploading
                    ? "linear-gradient(135deg, rgba(255, 193, 7, 0.95) 0%, rgba(255, 152, 0, 0.95) 100%)"
                    : "linear-gradient(135deg, rgba(96, 147, 157, 0.3) 0%, rgba(76, 127, 137, 0.3) 100%)",
                  boxShadow: selectedAvatar && !isUploading
                    ? "0 4px 16px rgba(255, 193, 7, 0.5)"
                    : "0 2px 8px rgba(0, 0, 0, 0.2)",
                  border: selectedAvatar && !isUploading
                    ? "1.5px solid rgba(255, 200, 50, 0.5)"
                    : "1.5px solid rgba(138, 206, 224, 0.2)",
                  color: selectedAvatar && !isUploading ? "#5A3800" : "#FFFFFF50",
                  textShadow: selectedAvatar && !isUploading
                    ? "0 1px 0 rgba(255, 255, 255, 0.2)"
                    : "none",
                  cursor: selectedAvatar && !isUploading ? "pointer" : "not-allowed",
                  opacity: selectedAvatar && !isUploading ? 1 : 0.6,
                }}
              >
                {isUploading ? "در حال آپلود..." : "تایید"}
              </motion.button>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
