"use client";

import React, { useState } from "react";
import { ChevronDown, ChevronUp } from "react-feather";

import CouponModal from "@/components/modal/coupon/CouponModal";
import { formatDate } from "@/utils/helper";


interface CouponItem {
  code?: string;
  title: string;
  description: string;
  brand_image?: string;
  image_url?: string;
  txt_img?: string;
  deeplink?: string;
  validthru?: string | null;
  source?: string;
  type?: string;
  cashback_value?: string;
  merchant?: string;
  per_or_dollar_value?: string | number;
  category_id?: string | number;
  coupon_used?: number;
  last_validated?: string;
}

interface CouponListProps {
  coupons: CouponItem[];
  merchantRedirectLink?: string;
  showBestDeal?: boolean;
  emptyMessage?: string;
  isDirectMerchant?: boolean;
  store?: string | null | undefined;
}

const CouponList: React.FC<CouponListProps> = ({
  coupons = [],
  // merchantRedirectLink = "",
  showBestDeal = false,
  emptyMessage = "No Offers Available",
  // isDirectMerchant = false,
  store = ''
}) => {
  const [openCollapseIndex, setOpenCollapseIndex] = useState<number | null>(
    null
  );
  const [isCouponModalOpen, setIsCouponModalOpen] = useState(false);
  const [selectedCoupon, setSelectedCoupon] = useState<any>(null);

  const openCouponModal = (couponData: any) => {
    setSelectedCoupon(couponData);
    setIsCouponModalOpen(true);
  };

  const closeCouponModal = () => {
    setIsCouponModalOpen(false);
    setSelectedCoupon(null);
  };

  if (!coupons || coupons?.length === 0) {
    return (
      <div className="shadow-sm bg-white border p-3 mb-3">
        <div className="row justify-content-center align-items-center">
          <div className="col-12">
            <h3 className="coupons-title">{emptyMessage}</h3>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="coupons-block-list">
      {coupons?.map((all: CouponItem, i: number) => {
        const title =
          all?.title && all.title?.trim()?.length <= 200
            ? all.title.trim()
            : "";
        const img_url = all?.brand_image || all?.image_url;
        const txt_img = all?.txt_img;
        const classMain =
          i === 0 && showBestDeal
            ? "shadow bg-white rounded-3 mb-3 top-offer-coupon-block"
            : "shadow-sm bg-white border rounded-3 p-3 mb-3";
        const class2 =
          i === 0 && showBestDeal
            ? "col-xxl-6 col-xl-5 col-lg-8 col-md-8"
            : "col-xxl-9 col-xl-9 col-lg-9 col-md-9";
        const url = all?.deeplink;
        const coupon_used = all.coupon_used || 0;
        const last_validated = all.last_validated || "";

        return (
          <a
            key={i}
            href="#"
            onClick={(e) => e.preventDefault()}
            className="couponModal"
          >
            <div className={classMain}>
              {i === 0 && showBestDeal ? (
                <>
                  <div className="d-flex justify-content-between align-items-center py-1 px-5 border">
                    <div className="col-xxl-4">
                      <p className="fw-bold text-uppercase text-md-start text-center">
                        Today&apos;s best offer
                      </p>
                    </div>
                    <div className="col-xxl-4">
                      <p className="fw-bold text-uppercase text-md-end text-center">
                        {new Date().toLocaleDateString("en-US", {
                          month: "short",
                          day: "2-digit",
                          year: "numeric",
                        })}
                      </p>
                    </div>
                  </div>
                  <hr className="my-0" />
                </>
              ) : null}

              <div className="row justify-content-center align-items-center p-3 position-relative">
                {i === 0 && showBestDeal ? (
                  <div className="col-xxl-3 col-xl-3 col-lg-4 col-md-4 col-sm-12 col-12 mb-3 mb-xl-0  d-flex justify-content-center align-items-center">
                    <div className="offers-tag">
                      <h4 className="text-white fw-bold">
                        BEST <br /> DEAL
                      </h4>
                      <div className="tag-block"></div>
                    </div>
                  </div>
                ) : null}

                <div
                  className={`${class2} col-sm-12 mt-xl-0 mt-4 text-md-left text-center`}
                >
                  <h3 className="coupons-title font-size-18">{title}</h3>
                  <div className="coupon-info">
                    {title === all.description ? "" : all.description}
                  </div>
                </div>

                <div className="col-xxl-3 col-xl-4 col-lg-12 col-md-12 col-sm-12 col-12 text-center mt-xl-0 mt-4">
                  <div className="mb-2">
                    <button
                      type="button"
                      className="shadow-sm btn-code2 w-100 rounded-0"
                      onClick={() =>
                        openCouponModal({
                          title: all?.title,
                          code: all?.code,
                          description: all?.description,
                          imgUrl: img_url,
                          url,
                          merchant: all?.merchant,
                          store,
                          txt_img
                        })
                      }
                    >
                      {all?.code ? "Get Coupon" : "Get Deal"}
                    </button>
                  </div>
                </div>
              </div>

              {i === 0 && showBestDeal ? (
                <div className="row justify-content-between">
                  <div className="offset-xxl-3 offset-xl-3 offset-lg-0 offset-md-0 col-xxl-9 col-xl-12 mt-xl-3">
                    <div className="row">
                      <div className="col-xxl-8 col-xl-8 col-lg-8 col-md-8 col-sm-12 col-12 mb-0"></div>
                      <div className="col-xxl-4 col-xl-4 col-lg-4 col-md-4 col-sm-12 col-12 mb-0">
                        <p className="pe-2 mb-2 font-size-13 text-xl-end text-lg-end text-md-end text-center">
                          Ends {formatDate(all?.validthru)}
                        </p>
                      </div>
                    </div>
                  </div>
                </div>
              ) : (
                <>
                  <hr />
                  <div className="row justify-content-between px-md-3 px-0">
                    <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 co-12">
                      <div className="dealsInfo">
                        <div className="usage">Used {coupon_used} Times</div>
                        <div>
                          <button
                            type="button"
                            className="btn btn-link p-0 text-decoration-none"
                            style={{ color: "black", fontSize: "14px" }}
                            onClick={() =>
                              setOpenCollapseIndex(
                                openCollapseIndex === i ? null : i
                              )
                            }
                          >
                            Details & Exclusions
                            {openCollapseIndex === i ? (
                              <ChevronUp size={20} />
                            ) : (
                              <ChevronDown size={20} />
                            )}
                          </button>
                        </div>
                      </div>

                      {openCollapseIndex === i && (
                        <div className="collapse show">
                          <div className="row">
                            <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-12 col-12">
                              <h6 className="my-2">Deal Stats</h6>
                              <ul className="dates">
                                <li>
                                  <span>Expires:</span>{" "}
                                  {all?.validthru}
                                </li>
                                <li>
                                  <span>Last Validated:</span> {last_validated}
                                </li>
                              </ul>
                            </div>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                </>
              )}
            </div>
          </a>
        );
      })}

      {/* Coupon Modal Integration */}
      <CouponModal
        isOpen={isCouponModalOpen}
        onClose={closeCouponModal}
        couponData={selectedCoupon}
      />
    </div>
  );
};

export default CouponList;
