import Image from "next/image";
import { Mail } from "react-feather";

import ImageWithFallback from "@/components/common/ImageWithFallback";
import { getShopProductDetailsServer } from "@/services/shop.service.server";
import config from "@/utils/config";

const defaultImage = config.APP_CONFIG.DEFAULT_IMG;

type Props = {
  params: Promise<{ id: string; slug: string }>;
};

export default async function ProductDetailsPage({ params }: Props) {
  const resolvedParams = await params;
  const pid = resolvedParams.id;
  const slug = resolvedParams.slug || "";

  const data = (await getShopProductDetailsServer(pid)) || {};
 

  const cleanTitleFromSlug =
    decodeURIComponent(slug).replace(/-/g, " ").replace(/\s+/g, " ").trim() ||
    "N/A";

  const fallbackProduct = {
    id: pid,
    product_name: cleanTitleFromSlug,
    price: null,
    image_small: defaultImage,
    description_string: "Details not available.",
    redirect_url: "#",
    category: "N/A",
    category_display: "N/A",
    feature: "{}",
  };

  const productDetail =
    data?.success && data?.product_details
      ? data.product_details
      : fallbackProduct;

  const redirect_url=data?.success ? data.redirect_url : fallbackProduct.redirect_url

  let rawFeatures: Record<string, any> = {};
  try {
    rawFeatures = JSON.parse(productDetail?.feature || "{}");
  } catch {
    rawFeatures = {};
  }

  const features = Object.fromEntries(
    Object.entries(rawFeatures).map(([key, value]) => [
      key.charAt(0).toUpperCase() + key.slice(1),
      value,
    ])
  );

  return (
    <div className="lightBg">
      <style>{`
          .icon-row {
            display: flex;
            gap: 5px;
          }
          .icon-row img {
            width: 70px;
            height: 70px;
            object-fit: contain;
          }
      `}</style>

      <section
        className="productDetailSection pt-5 pb-4"
        id="productDetailSection"
      >
        <div className="container">
          <div className="bg-white p-4">
            <div className="row align-items-center">
              {/* LEFT IMAGE */}
              <div className="col-xl-6 col-md-5">
                <div className="productDetailImg">
                  <ImageWithFallback
                    src={productDetail?.image_small || defaultImage}
                    alt={productDetail?.product_name || "img"}
                    height={600}
                    width={600}
                    className="w-100 h-100"
                  />
                </div>
              </div>

              {/* RIGHT PRODUCT INFO */}
              <div className="col-xl-6 col-md-7">
                <div className="webContent productDetailContent">
                  <h2 className="mainHeading">
                    {productDetail?.product_name || ""} ($
                    {Number(productDetail?.price ?? 0).toFixed(2)} Value)
                  </h2>
                  <h3 className="subHeading font-weight-bold mt-md-4">
                    ${Number(productDetail?.price ?? 0).toFixed(2)}
                  </h3>

                  <table className="table productDetailTable my-3">
                    <tbody>
                      <tr>
                        <th>Category</th>
                        <th>--</th>
                        <td>
                          {productDetail?.category_display ||
                            productDetail?.category}
                        </td>
                      </tr>
                      <tr>
                        <th>Share</th>
                        <th>--</th>
                        <td>
                          <a
                            href={`mailto:?Subject=${encodeURIComponent(
                              productDetail?.product_name
                            )}&Body=${encodeURIComponent(
                              `Check this product: /product-details/${
                                productDetail?.id
                              }/${encodeURIComponent(
                                productDetail?.product_name?.replace(
                                  /\s+/g,
                                  "-"
                                )
                              )}`
                            )}`}
                          >
                            <Mail
                              size={16}
                              strokeWidth={2.5}
                              className="redColor"
                            />
                          </a>
                        </td>
                      </tr>
                    </tbody>
                  </table>

                  <hr />

                  {data?.success ? (
                    <a href={redirect_url} target="_blank">
                      <button className="button btn-first shadow-none text-white mt-3">
                        Add to cart
                      </button>
                    </a>
                  ) : null}
                </div>
              </div>
            </div>

            {/* DESCRIPTION & SPECIFICATION */}
            <div className="row align-items-center mt-5">
              <div className="col-md-12">
                <ul
                  className="nav nav-pills mb-3 tabingStyle"
                  id="productDetailTabs"
                >
                  <li className="nav-item">
                    <a
                      className="nav-link active"
                      id="productDescriptionTab"
                      data-bs-toggle="pill"
                      href="#productDescription"
                    >
                      Description
                    </a>
                  </li>
                  <li className="nav-item">
                    <a
                      className="nav-link"
                      id="productInfoTab"
                      data-bs-toggle="pill"
                      href="#productInfo"
                    >
                      Specification
                    </a>
                  </li>
                </ul>

                <div className="tab-content" id="productDetailsTabsContent">
                  {/* DESCRIPTION TAB */}
                  <div
                    className="tab-pane fade show active"
                    id="productDescription"
                  >
                    <div className="webContent">
                      <p>{productDetail?.description_string || "N/A"}</p>
                    </div>
                  </div>

                  {/* SPECIFICATION TAB */}
                  <div className="tab-pane fade" id="productInfo">
                    <div className="row">
                      <div className="col-12">
                        <table className="table table-bordered">
                          <tbody>
                            {Object.entries(features).map(
                              ([feature, value]) => (
                                <tr key={feature}>
                                  <td className="text-blue">
                                    <b>{feature?.replace(/_/g, " ")}</b>
                                  </td>
                                  <td className="text-right">
                                    {feature?.toLowerCase() ===
                                      "additionalimages" &&
                                    Array.isArray(value) ? (
                                        <div className="icon-row">
                                          {value.map((img: string, i: number) => (
                                            <Image
                                              key={i}
                                              src={img || defaultImage}
                                              alt={`icon-${i}`}
                                              width={70}
                                              height={70}
                                            />
                                          ))}
                                        </div>
                                      ) : (
                                        <>{String(value)}</>
                                      )}
                                  </td>
                                </tr>
                              )
                            )}
                          </tbody>
                        </table>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  );
}
