import { useState } from "react";
import { motion, AnimatePresence } from "motion/react";
import { ImageIcon, Video } from "lucide-react";
import { SubmitFormProps, getTopicConfig } from "../../../config/topicConfig";
import { MediaUploadBox } from "./shared/MediaUploadBox";
import { TeammatesSection, Teammate } from "./shared/TeammatesSection";
import { FormInput } from "./shared/FormInput";
import { uploadImage, uploadFile, submitMission } from "../../../services/feedService";
import { useProfile } from "../../context/ProfileContext";

// Helper function to generate unique IDs
const generateId = () => `teammate-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

export function ImageVideoForm({ topicId, topicTitle, onSubmit }: SubmitFormProps) {
  const topicConfig = getTopicConfig(topicId);
  const { refreshProfile } = useProfile();
  
  // ===== Form Fields State =====
  const [title, setTitle] = useState("");
  const [learnings, setLearnings] = useState("");
  
  // ===== Teammates State (with unique IDs and verification) =====
  const [teammates, setTeammates] = useState<Teammate[]>([{ id: generateId(), phone: "" }]);
  
  // ===== Media State =====
  const [mediaType, setMediaType] = useState<"image" | "video">("image");
  const [uploadedImage, setUploadedImage] = useState<string | null>(null);
  const [uploadedImageFile, setUploadedImageFile] = useState<File | null>(null);
  const [uploadedVideo, setUploadedVideo] = useState<{ url: string; name: string } | null>(null);
  const [uploadedVideoFile, setUploadedVideoFile] = useState<File | null>(null);
  const [videoCover, setVideoCover] = useState<string | null>(null);
  const [videoCoverFile, setVideoCoverFile] = useState<File | null>(null);

  // ===== Loading State =====
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<string>("");

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

  const handleVideoUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      setUploadedVideoFile(file);
      const url = URL.createObjectURL(file);
      setUploadedVideo({ url, name: file.name });
      setVideoCover(null);
      setVideoCoverFile(null);
    }
  };

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

  const handleSwitchMediaType = (type: "image" | "video") => {
    setMediaType(type);
    setUploadedImage(null);
    setUploadedImageFile(null);
    setUploadedVideo(null);
    setUploadedVideoFile(null);
    setVideoCover(null);
    setVideoCoverFile(null);
  };

  // ===== Teammates Handlers =====
  const handleAddTeammate = () => {
    setTeammates([...teammates, { id: generateId(), phone: "" }]);
  };

  const handleRemoveTeammate = (id: string) => {
    const filtered = teammates.filter((t) => t.id !== id);
    setTeammates(filtered.length > 0 ? filtered : [{ id: generateId(), phone: "" }]);
  };

  const handleTeammateChange = (id: string, value: string) => {
    setTeammates(teammates.map((t) => (t.id === id ? { ...t, phone: value, fullName: undefined, userId: undefined, error: undefined } : t)));
  };

  const handleTeammateVerify = (id: string, fullName: string, userId: string, error?: string) => {
    setTeammates(teammates.map((t) => (t.id === id ? { ...t, fullName, userId, error } : t)));
  };

  const handleSubmit = async () => {
    if (isSubmitting) return;
    
    setIsSubmitting(true);

    try {
      let imageFilename = "";
      let filmFilename = "";

      // برای ویدیو: آپلود فیلم و کاور
      if (mediaType === "video") {
        if (!uploadedVideoFile || !videoCoverFile) {
          alert("لطفاً ویدیو و کاور آن را انتخاب کنید");
          setIsSubmitting(false);
          return;
        }

        // آپلود فیلم
        setUploadProgress("در حال آپلود ویدیو...");
        const videoFilename = await uploadFile(uploadedVideoFile);
        if (!videoFilename) {
          alert("خطا در آپلود ویدیو");
          setIsSubmitting(false);
          setUploadProgress("");
          return;
        }
        filmFilename = videoFilename;

        // آپلود کاور (به عنوان image)
        setUploadProgress("در حال آپلود کاور ویدیو...");
        const coverFilename = await uploadImage(videoCoverFile);
        if (!coverFilename) {
          alert("خطا در آپلود کاور ویدیو");
          setIsSubmitting(false);
          setUploadProgress("");
          return;
        }
        imageFilename = coverFilename;
      }
      // برای تصویر: فقط آپلود تصویر
      else if (mediaType === "image") {
        if (uploadedImageFile) {
          setUploadProgress("در حال آپلود تصویر...");
          const filename = await uploadImage(uploadedImageFile);
          if (!filename) {
            alert("خطا در آپلود تصویر");
            setIsSubmitting(false);
            setUploadProgress("");
            return;
          }
          imageFilename = filename;
        }
      }

      // Get verified user IDs and join with comma
      const verifiedUserIds = teammates
        .filter((t) => t.userId)
        .map((t) => t.userId)
        .join(",");

      // Get workflow_ID from localStorage (این همان mission_done_workflowID است)
      const workflowID = localStorage.getItem("current_workflow_ID") || "";

      // ثبت نهایی ماموریت
      setUploadProgress("در حال ثبت ماموریت...");
      const result = await submitMission({
        title: title || "",
        mission_type: topicTitle,
        mission_done_workflowID: workflowID,
        description: learnings || "",
        film: filmFilename,
        image: imageFilename,
        audio: "",
        team_member: verifiedUserIds,
      });

      if (result.success) {
        // بروزرسانی پروفایل (برای سکه‌های جدید)
        await refreshProfile();
        
        // فراخوانی onSubmit برای نمایش modal و هدایت به feed
        onSubmit({
          topicId,
          title,
          learnings,
          teammates: verifiedUserIds ? [verifiedUserIds] : [],
          mediaType,
          uploadedImage,
          uploadedVideo,
          videoCover,
        });
      } else {
        alert(result.message || "خطا در ثبت ماموریت");
      }
    } catch (error) {
      console.error("Error submitting:", error);
      alert("خطا در ثبت ماموریت");
    } finally {
      setIsSubmitting(false);
      setUploadProgress("");
    }
  };

  const isSubmitDisabled = mediaType === "video" && uploadedVideo !== null && videoCover === null;

  return (
    <div className="space-y-6" dir="rtl">
      {/* Media Type Tabs */}
      <div>
        <label className="mb-3 block text-sm font-bold text-[#FBE7F5]">رسانه چالش</label>
        <div
          className="flex rounded-2xl p-1 mb-4"
          style={{
            backgroundImage:
              "linear-gradient(180deg, rgba(46, 27, 61, 0.92) 0%, rgba(35, 24, 62, 0.94) 100%), linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)",
            backgroundOrigin: "border-box",
            backgroundClip: "padding-box, border-box",
            border: "0.5px solid transparent",
          }}
        >
          {(["image", "video"] as const).map((type) => (
            <motion.button
              key={type}
              whileTap={{ scale: 0.96 }}
              onClick={() => handleSwitchMediaType(type)}
              className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-bold transition-all duration-300"
              style={
                mediaType === type
                  ? {
                      background:
                        "linear-gradient(135deg, rgba(174, 117, 255, 0.96) 0%, rgba(138, 82, 238, 0.95) 46%, rgba(102, 55, 204, 0.94) 100%)",
                      color: "#FFFFFF",
                      boxShadow: "0 0 18px rgba(155,108,241,0.4)",
                    }
                  : { color: "rgba(251,231,245,0.72)" }
              }
            >
              {type === "image" ? (
                <>
                  <ImageIcon className="w-4 h-4" /> عکس
                </>
              ) : (
                <>
                  <Video className="w-4 h-4" /> ویدیو
                </>
              )}
            </motion.button>
          ))}
        </div>

        <AnimatePresence mode="wait">
          {/* Image Upload */}
          {mediaType === "image" && (
            <motion.div
              key="image-upload"
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -8 }}
              transition={{ duration: 0.25 }}
            >
              <MediaUploadBox
                type="image"
                uploadedFile={uploadedImage}
                onUpload={handleImageUpload}
                onRemove={() => setUploadedImage(null)}
              />
            </motion.div>
          )}

          {/* Video Upload */}
          {mediaType === "video" && (
            <motion.div
              key="video-upload"
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -8 }}
              transition={{ duration: 0.25 }}
              className="space-y-4"
            >
              <MediaUploadBox
                type="video"
                uploadedFile={uploadedVideo?.url || null}
                onUpload={handleVideoUpload}
                onRemove={() => {
                  setUploadedVideo(null);
                  setVideoCover(null);
                }}
                fileName={uploadedVideo?.name}
              />

              {/* Video Cover - shown only after video is selected */}
              <AnimatePresence>
                {uploadedVideo && (
                  <motion.div
                    initial={{ opacity: 0, height: 0 }}
                    animate={{ opacity: 1, height: "auto" }}
                    exit={{ opacity: 0, height: 0 }}
                    transition={{ duration: 0.3 }}
                  >
                    <MediaUploadBox
                      type="image"
                      uploadedFile={videoCover}
                      onUpload={handleVideoCoverUpload}
                      onRemove={() => setVideoCover(null)}
                      label="کاور ویدیو"
                      required
                    />
                  </motion.div>
                )}
              </AnimatePresence>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Teammates - Only show if config requires it */}
      {topicConfig.requiresTeammates && (
        <TeammatesSection
          teammates={teammates}
          onAdd={handleAddTeammate}
          onRemove={handleRemoveTeammate}
          onChange={handleTeammateChange}
          onVerify={handleTeammateVerify}
        />
      )}

      {/* Title */}
      <FormInput
        label="عنوان چالش"
        value={title}
        onChange={setTitle}
        placeholder="عنوان چالش خود را وارد کنید..."
      />

      {/* Learnings */}
      <FormInput
        label="از این چالش چه چیزی یاد گرفتیم"
        value={learnings}
        onChange={setLearnings}
        placeholder="توضیحات خود را وارد کنید..."
        multiline
        rows={6}
      />

      {/* Submit Button */}
      <motion.button
        whileTap={{ scale: 0.95 }}
        onClick={handleSubmit}
        disabled={isSubmitDisabled || isSubmitting}
        className="w-full py-4 rounded-full text-white text-base font-bold mb-6 transition-opacity"
        style={{
          backgroundImage: isSubmitDisabled || isSubmitting
            ? "linear-gradient(145deg, rgba(72, 58, 105, 0.72) 0%, rgba(42, 35, 77, 0.76) 100%)"
            : "linear-gradient(90deg, rgba(255,139,91,1) 0%, rgba(238,91,166,1) 45%, rgba(147,78,255,1) 100%), linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)",
          backgroundOrigin: "border-box",
          backgroundClip: "padding-box, border-box",
          boxShadow: isSubmitDisabled || isSubmitting
            ? "inset 0 1px 0 rgba(255,255,255,0.12)"
            : "0 10px 26px rgba(196, 87, 255, 0.35), inset 0 1px 0 rgba(255,255,255,0.35)",
          border: "1px solid transparent",
        }}
      >
        {isSubmitDisabled ? "ابتدا کاور ویدیو را انتخاب کنید" : isSubmitting ? "در حال ارسال..." : "ثبت نهایی چالش"}
      </motion.button>

      {/* Upload Progress Message */}
      {uploadProgress && (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="text-center mb-4 p-4 rounded-2xl"
          style={{
            backgroundImage:
              "linear-gradient(180deg, rgba(46, 27, 61, 0.88) 0%, rgba(35, 24, 62, 0.92) 100%), linear-gradient(120deg, #7c3aed 0%, #f97316 58%, #facc15 100%)",
            backgroundOrigin: "border-box",
            backgroundClip: "padding-box, border-box",
            border: "0.5px solid transparent",
          }}
        >
          <div className="flex items-center justify-center gap-3">
            <motion.div
              animate={{ rotate: 360 }}
              transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
              className="w-5 h-5 border-2 border-[#D8B4FE] border-t-transparent rounded-full"
            />
            <span className="text-[#FBE7F5] font-bold text-sm">{uploadProgress}</span>
          </div>
        </motion.div>
      )}
    </div>
  );
}
