"use client"

import { ShoppingCart } from "lucide-react";
import { HardHat } from "lucide-react";
import { Tag } from "lucide-react";
import { useLocale } from "next-intl";
import Link from "next/link";
import ContactModal from "../ContactUs";
import { useState } from "react";
import { useTranslations } from "next-intl";
import BrandInfo from "./BrandInfo";
import { Share2 } from "lucide-react";
import { toast } from "react-toastify";


export default function ProductInfo({ title, price, discount, showPrice, category, summery, brand, subcategories }) {

  const locale = useLocale()

  // Determine the currency symbol based on the locale
  const currencySymbol = locale === "ar-OM" ? "ريال" : "$";
  const CategoryIcon = category.slug === "fmcg" ? ShoppingCart : HardHat
  const discountedPrice = discount ? price * (1 - discount / 100) : price;


  const [open, setOpen] = useState(false);
  const openModal = () => {
    setOpen(true);
  };
  const closeModal = () => {
    setOpen(false);
  }

  const t = useTranslations("ContactModal")

  const shareLink = async () => {
    if (navigator.share) {
      navigator.share({
        title: title,
        text: 'Check out this on Advanced Horizon !',
        url: window.location.href,
      })

    } else if (navigator.clipboard) {
      try {
        await navigator.clipboard.writeText(text);
        toast.success("link copied!")
      } catch (err) {
        console.error('Failed to copy: ', err);
      }
    } else {
      const tempInput = document.createElement('input');
      tempInput.style.position = 'absolute';
      tempInput.style.left = '-9999px';
      tempInput.value = window.location.href;
      document.body.appendChild(tempInput);
      tempInput.select();
      document.execCommand('copy');
      document.body.removeChild(tempInput);
      toast.success("link copied!")
    }

  }

  return (
    <div className="w-full">
      <ContactModal close={closeModal} open={open} />
      <div className="flex items-start w-full justify-between lg:flex-row flex-col-reverse gap-4">
        <div>
          <h1 className="text-3xl font-bold">{title}</h1>
          <div className="flex gap-2">
            <Link href={`/products/${category.slug}`} className="mt-4 flex items-center underline">
              <span className={`inline-flex items-center rounded-md bg-gray-100 hover:bg-gray-200 px-2.5 py-0.5 text-sm font-medium text-gray-800 ltr`}>
                <CategoryIcon className="h-4 w-4 mx-1" />
                {category.title}
              </span>
            </Link>
            {
              brand?.slug &&
            <Link href={`/products/${brand?.slug}`} className="mt-4 flex items-center underline">
              <span className={`inline-flex items-center rounded-md bg-gray-100 hover:bg-gray-200 px-2.5 py-0.5 text-sm font-medium text-gray-800 ltr`}>
             
                {brand.title}
              </span>
            </Link>
            }
            {
              [...(brand?.subcategories ?? []), ...(subcategories ?? [])].map(sub => (

                <Link key={sub.documentId} href={`/products/${sub.slug}`} className="mt-4 flex items-center underline">
                  <span className={`inline-flex items-center rounded-md bg-gray-100 hover:bg-gray-200 px-2.5 py-0.5 text-sm font-medium text-gray-800 ltr`}>
                    
                    {sub.title}
                  </span>
                </Link>
              ))
            }
          </div>
          <p className="text-sm opacity-75">
            {
              summery
            }
          </p>
          {showPrice && (
            <div className="mt-4">
              {discount ? (
                <div className="flex items-center">
                  <span className="text-2xl font-bold text-primary">
                    {locale === "ar-OM" ? (
                      <>
                        {discountedPrice.toFixed(2)} {currencySymbol}
                      </>
                    ) : (
                      <>
                        {currencySymbol}
                        {discountedPrice.toFixed(2)}
                      </>
                    )}
                  </span>
                  <span className="ml-2 text-lg text-gray-500 line-through">
                    {locale === "ar-OM" ? (
                      <>
                        {price.toFixed(2)} {currencySymbol}
                      </>
                    ) : (
                      <>
                        {currencySymbol}
                        {price.toFixed(2)}
                      </>
                    )}
                  </span>
                  <span className="ml-2 inline-flex items-center rounded-md bg-red-100 px-2.5 py-0.5 text-sm font-medium text-red-800">
                    {discount}% OFF
                  </span>
                </div>
              ) : (
                <span className="text-2xl font-bold text-primary">
                  {locale === "ar-OM" ? (
                    <>
                      {price.toFixed(2)} {currencySymbol}
                    </>
                  ) : (
                    <>
                      {currencySymbol}
                      {price.toFixed(2)}
                    </>
                  )}
                </span>
              )}
            </div>
          )}
        </div>
        <div>
          {
            brand && (
              <BrandInfo brand={brand} />
            )
          }
        </div>
      </div>
      <div className="mt-10 w-full border-t pt-10 flex gap-2 items-center">
        {/* Replaced Button with Tailwind CSS */}
        <button onClick={openModal} className="w-full lg:w-fit px-8 ltr flex items-center justify-center py-2 bg-gradient-to-r from-primary-600 to-primary-400 text-white rounded-md hover:bg-primary-dark transition-colors">
          <ShoppingCart className="mr-2 h-4 w-4" /> {t("cta")}
        </button>
        <button className="border p-2 rounded-lg flex flex-col items-center justify-center shadow-none text-black/60" onClick={() => shareLink()}>
          <Share2 size={24} />
        </button>
      </div>
    </div>
  );
}