"use client";

import React, { useEffect, useState } from "react";
import Image from "next/image";
import Profile from "@/assets/images/offer.png";
import { useGlobalContext } from "@/context/Provider";
import { ScrollArea } from "../ui/scroll-area";
import { cn } from "@/lib/utils";

interface Props {
  open: boolean;
  onClose: () => void;
  coupons: any[];
  applyCoupon: (item: any) => void;
  discount: any;
  setDiscount: React.Dispatch<React.SetStateAction<any>>;
}

const BottomSheetCoupon: React.FC<Props> = ({
  open,
  onClose,
  coupons,
  applyCoupon,
  discount,
  setDiscount,
}) => {
  const { Toast, userInfo } = useGlobalContext();
  const isLoggedIn = !!userInfo?.access_token;
  const [couponCode, setCouponCode] = useState("");
  const [errorMessage, setErrorMessage] = useState("");

  //   useEffect(() => {
  //     if (open) {
  //       setTimeout(() => {
  //         try {
  //           (window.adsbygoogle = window.adsbygoogle || []).push({});
  //           const wrapper = document.getElementById("coupon-ad");
  //           if (wrapper) wrapper.style.height = "120px";
  //         } catch {}
  //       }, 100);
  //     }
  //   }, [open]);

  const handleApply = () => {
    if (!isLoggedIn) {
      Toast.error("Please log in to apply coupon");
      return;
    }
    const found = coupons.find((c) => c.code === couponCode.trim());

    if (!found) {
      setErrorMessage("Invalid coupon");
      Toast.error("Invalid coupon");
      return;
    }

    applyCoupon(found);
    setErrorMessage("");
    onClose();
  };

  const toggleCoupon = (item: any) => {
    if (discount?._id === item._id) {
      setDiscount(null);
      onClose();
    } else {
      if (!isLoggedIn) {
        Toast.error("Please log in to apply coupon");
        return;
      }
      applyCoupon(item);
      onClose();
    }
  };

  return (
    <div
      className={cn(
        "fixed inset-x-0 bottom-0 bg-white shadow-2xl rounded-t-2xl transition-transform duration-300 z-[200]",
        open ? "translate-y-0" : "translate-y-full"
      )}
      style={{ height: "85vh" }}
    >
      <div className="flex justify-between items-center p-4 border-b">
        <h2 className="font-semibold text-lg">Apply Coupon</h2>
        <button onClick={onClose} className="text-xl">×</button>
      </div>

      <div className="w-full flex justify-center p-4">
        {/* {open && (
        <div
          id="coupon-ad"
          className="w-full max-w-xl overflow-hidden transition-all duration-300 rounded-lg"
          style={{ height: "0px" }}
        >
          <ins
            className="adsbygoogle"
            style={{ display: "block" }}
            data-ad-client="ca-pub-6410961539876945"
            data-ad-slot="7558939743"
            data-adtest="on"
            data-ad-format="auto"
            data-full-width-responsive="true"
          />
        </div>
        )} */}
      </div>
      <div className="p-4 space-y-2">
        <div className="flex gap-3">
          <input
            className="flex-1 border px-3 py-2 rounded-md"
            placeholder="Enter Coupon Code"
            value={couponCode}
            onChange={(e) => setCouponCode(e.target.value)}
          />

          <button
            disabled={!isLoggedIn}
            onClick={handleApply}
            title={!isLoggedIn ? "Please log in to apply coupon" : ""}
            className={`px-5 rounded-md transition-all ${
              !isLoggedIn
                ? "bg-gray-300 text-gray-500 cursor-not-allowed"
                : "bg-black text-white hover:bg-black/90"
            }`}
          >
            Apply
          </button>
        </div>

        {errorMessage && (
          <p className="text-red-500 text-sm">{errorMessage}</p>
        )}
      </div>
      <ScrollArea className="h-[50vh] px-4 pb-6">
        {coupons.length === 0 ? (
          <p className="text-gray-500 text-center mt-10">No coupons available</p>
        ) : (
          <div className="space-y-4">
            {coupons.map((item) => (
              <div
                key={item._id}
                className="flex justify-between items-center border rounded-lg p-4 bg-white shadow-sm"
              >
                <div className="flex items-start gap-3">
                  <Image src={Profile} alt="offer" className="w-10 h-10" />

                  <div>
                    <h3 className="font-semibold">{item.code}</h3>
                    <p className="text-gray-500 text-sm">{item.description}</p>
                  </div>
                </div>

                <button
                  disabled={!isLoggedIn && discount?._id !== item._id}
                  title={!isLoggedIn ? "Please log in to apply coupon" : ""}
                  className={`font-medium transition-all ${
                    discount?._id === item._id
                      ? "text-red-500"
                      : !isLoggedIn
                      ? "text-gray-400 cursor-not-allowed"
                      : "text-black hover:text-primary"
                  }`}
                  onClick={() => toggleCoupon(item)}
                >
                  {discount?._id === item._id ? "Remove" : "Apply"}
                </button>

              </div>
            ))}
          </div>
        )}
      </ScrollArea>
    </div>
  );
};

export default BottomSheetCoupon;



