import { useState } from "react";
import { motion } from "motion/react";
import { SubmitFormProps, getTopicConfig } from "../../../config/topicConfig";
import { MediaUploadBox } from "./shared/MediaUploadBox";
import { FormInput } from "./shared/FormInput";
import { SupervisorRequestSection } from "./shared/SupervisorRequestSection";
import { uploadImage, submitMission } from "../../../services/feedService";
import { useProfile } from "../../context/ProfileContext";

export function ImageWithSupervisorForm({ topicId, topicTitle, onSubmit, doingMission }: SubmitFormProps) {
  const topicConfig = getTopicConfig(topicId);
  const { refreshProfile } = useProfile();

  // ===== Form Fields State =====
  const [title, setTitle] = useState("");
  const [learnings, setLearnings] = useState("");

  // ===== Media State =====
  const [uploadedImage, setUploadedImage] = useState<string | null>(null);
  const [uploadedImageFile, setUploadedImageFile] = useState<File | null>(null);

  // ===== Supervisor State =====
  const [supervisorPhone, setSupervisorPhone] = useState("");
  const [supervisorCode, setSupervisorCode] = useState("");

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

  // خواندن mobile و code از doingMission
  const initialMobile = doingMission?.mobile || "";
  const initialCode = doingMission?.code || "";

  // ===== Media Handler =====
  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);
    }
  };

  // ===== Supervisor Handler =====
  const handleSupervisorDataChange = (phone: string, code: string) => {
    setSupervisorPhone(phone);
    setSupervisorCode(code);
  };

  const handleSubmit = async () => {
    // Validate supervisor phone and code
    if (supervisorPhone.length < 10) {
      alert("لطفاً شماره تلفن ناظر را به طور کامل وارد کنید");
      return;
    }

    if (supervisorCode.length < 6) {
      alert("لطفاً کد تأیید 6 رقمی ناظر را وارد کنید");
      return;
    }

    if (isSubmitting) return;

    setIsSubmitting(true);

    try {
      // آپلود تصویر اگر وجود دارد
      let imageFilename = "";
      if (uploadedImageFile) {
        setUploadProgress("در حال آپلود تصویر...");
        const filename = await uploadImage(uploadedImageFile);
        if (filename) {
          imageFilename = filename;
        } else {
          alert("خطا در آپلود تصویر");
          setIsSubmitting(false);
          setUploadProgress("");
          return;
        }
      }

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

      // اگر شماره 10 رقمی است، صفر به اولش اضافه کن
      const normalizedPhone = supervisorPhone.length === 10 ? `0${supervisorPhone}` : supervisorPhone;

      // ثبت نهایی ماموریت (supervisor به عنوان team_member ارسال می‌شود)
      setUploadProgress("در حال ثبت ماموریت...");
      const result = await submitMission({
        title: title || "",
        mission_type: topicTitle,
        mission_done_workflowID: workflowID, // اینجا workflow_ID را ارسال می‌کنیم
        description: learnings || "",
        film: "",
        image: imageFilename,
        audio: "",
        team_member: "", // در آبخوری team_member باید خالی باشد
        enter_code: supervisorCode, // کد تایید ناظر
      });

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

  return (
    <div className="space-y-6" dir="rtl">
      {/* Image Upload */}
      <MediaUploadBox
        type="image"
        uploadedFile={uploadedImage}
        onUpload={handleImageUpload}
        onRemove={() => setUploadedImage(null)}
        label="تصویر چالش"
      />

      {/* Supervisor Request Section */}
      <SupervisorRequestSection
        onSupervisorDataChange={handleSupervisorDataChange}
        initialMobile={initialMobile}
        initialCode={initialCode}
      />

      {/* 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={supervisorPhone.length < 10 || supervisorCode.length < 6 || isSubmitting}
        className="w-full py-4 rounded-full text-white text-base font-bold mb-6"
        style={{
          backgroundImage: supervisorPhone.length >= 10 && supervisorCode.length >= 6 && !isSubmitting
            ? "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%)"
            : "linear-gradient(145deg, rgba(72, 58, 105, 0.72) 0%, rgba(42, 35, 77, 0.76) 100%)",
          backgroundOrigin: "border-box",
          backgroundClip: "padding-box, border-box",
          boxShadow: supervisorPhone.length >= 10 && supervisorCode.length >= 6 && !isSubmitting
            ? "0 10px 26px rgba(196, 87, 255, 0.35), inset 0 1px 0 rgba(255,255,255,0.35)"
            : "inset 0 1px 0 rgba(255,255,255,0.12)",
          border: "1px solid transparent",
          cursor: supervisorPhone.length >= 10 && supervisorCode.length >= 6 && !isSubmitting ? "pointer" : "not-allowed",
          opacity: isSubmitting ? 0.7 : 1,
        }}
      >
        {supervisorPhone.length < 10 || supervisorCode.length < 6
          ? "لطفاً شماره و کد ناظر را کامل کنید"
          : 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>
  );
}