"use client";

import { useState, useEffect } from "react";
import api from "@/api/axios";
import { toast } from "sonner";

export default function CouponModal({ isCouponOpen, onCloseCoupon }: any) {
  const [loading, setLoading] = useState(false);
  const [Couponcode, setCouponcode] = useState("");


  if (!isCouponOpen) return null;

  // دالة إرسال النموذج
  const handleSubmit = async (e: any) => {
    e.preventDefault();

    // التحقق من البيانات المطلوبة
    if (!Couponcode) {
      toast.info("الرجاء ملء جميع الحقول المطلوبة");
      return;
    }

    setLoading(true);

    try {
      const response = await api.post("/cart/apply-coupon", {
        coupon_code: Couponcode
      });

      if (response.data && response.data.success) {
        toast.success("تمت إضافة كود الخصم بنجاح!");
        onCloseCoupon();
        // إعادة تعيين النموذج
        setCouponcode(" ");
      } else {
        throw new Error(response.data?.message || "فشل في إضافة كود الخصم ");
      }
    } catch (error: any) {
      console.error("Error saving address:", error);

      // عرض رسالة الخطأ من الـ API إن وجدت
      if (error.response?.data?.message) {
        toast.error(`حدث خطأ: ${error.response.data.message}`);
      } else if (error.message) {
        toast.error(`حدث خطأ: ${error.message}`);
      } else {
        toast.error("حدث خطأ أثناء حفظ العنوان. الرجاء المحاولة مرة أخرى.");
      }
      // إذا كان الخطأ متعلقًا بالمصادقة (مثل token منتهي الصلاحية)
      if (error.response?.status === 401 || error.response?.status === 403) {
        console.error("Authentication error. Token might be invalid or expired.");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <>
      {/* خلفية سوداء */}
      <div
        onClick={onCloseCoupon}
        className="fixed inset-0 bg-black/40 z-40"
      />

      {/* المودال */}
      <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
        <form onSubmit={handleSubmit} className="bg-white rounded-[20px] w-full max-w-[500px] p-6 relative shadow-lg overflow-hidden max-h-[90vh]">
          <div className="relative flex items-center justify-start mb-4">
            <button
              type="button"
              onClick={onCloseCoupon}
              className="cursor-pointer"
            >
              <img src="/icons/right-arrow.svg" alt="إغلاق" />
            </button>
            <h2 className="absolute left-1/2 -translate-x-1/2 text-[18px] font-book text-basic-color">
              كود الخصم
            </h2>
          </div>

          <div className="w-full h-[1px] bg-[#F3F4F6] mb-6"></div>

          {/* كود الخصم */}
          <div className="mb-4 relative">
            <label className="block text-[14px] mb-2 font-book text-basic-color">
              كود الخصم
            </label>
            <input
              type="text"
              name="coupon_code"
              value={Couponcode}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                setCouponcode(e.target.value)
              }
              placeholder="كود الخصم"
              className="w-full border rounded-[12px] px-4 py-3 text-[14px] bg-[#F4F4F6] text-[#73737C] outline-none"
              style={{ borderColor: "rgba(0,0,0,0.1)" }}
              required
            />

            <img
              src="/icons/coupon.svg"
              alt=""
              className="absolute left-3 top-[42px]"
            />
          </div>

          {/* زر الحفظ */}
          <button
            type="submit"
            className={`w-full text-white font-bold rounded-[12px] py-3 text-[15px] ${loading ? 'opacity-70 cursor-not-allowed' : ''}`}
            style={{ background: "#FF2B77" }}
            disabled={loading}
          >
            {loading ? "جاري الحفظ..." : "حفظ "}
          </button>
        </form>
      </div>
    </>
  );
}