"use client";
import { useEffect, useState } from "react";
import { useLocale, useTranslations } from "next-intl";
import { RS } from "@/shared/Icons";
import { useDispatch } from "react-redux";
import { AppDispatch } from "@/store/store";
import { useForm, UseFormSetValue } from "react-hook-form";
import ShowAlertMixin from "@/shared/ShowAlertMixin";
import { getAllCartItems } from "@/store/cart.slice";
import { UseMutate } from "@/hooks/UseMutate";
import QuantityControl from "@/shared/quantity-control/QuantityControl";
import { Form } from "@/shared/ui/form";
import { products } from "@/interfaces/types";
import MediaWithFallback from "@/shared/MediaWithFallback";
import LocalePath from "@/shared/LocalePath";
import Fancybox from "@/shared/ui/Fancybox";
import {
  FacebookShareButton,
  InstapaperShareButton,
  WhatsappShareButton,
} from "next-share";
interface MyFormValues {
  amount: number;
}
export default function Product({ product }: { product: products }) {
  const t = useTranslations();
  const locale = useLocale();
  const dispatch = useDispatch<AppDispatch>();
  const [initialCount, setInitialCount] = useState(1);
  const [modalOpen, setModalOpen] = useState(false);
  const [shareUrl, setShareUrl] = useState("");

  const form = useForm<MyFormValues>({
    defaultValues: { amount: initialCount },
  });
  const { setValue }: { setValue: UseFormSetValue<any> } = form;
  const { mutate, isLoading: addToCartLoading } = UseMutate({
    endpoint: "client/carts/add",
    onSuccess: (responseData: any) => {
      ShowAlertMixin({
        icon: "success",
        title: responseData?.message,
      });
      dispatch(getAllCartItems());
    },
  });
  async function onSubmit(values: any) {
    const finalOut = {
      amount: values?.amount,
      product_id: product?.id,
    };
    mutate({ ...finalOut });
  }
  useEffect(() => {
    if (typeof window !== "undefined") {
      setShareUrl(new URL(window.location.href).toString());
    }
  }, []);
  return (
    <>
      <div className="container">
        <div className="flex items-center gap-2 mb-8 text-sm">
          <LocalePath
            href="/"
            className="text-text-secondary hover:text-primary transition-colors"
          >
            {t("NAV.home")}
          </LocalePath>
          <span className="text-text-secondary">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="lucide lucide-chevron-left"
            >
              <path d="m15 18-6-6 6-6"></path>
            </svg>
          </span>
          <LocalePath
            href={`/products?category_id=${product?.category?.id}`}
            className="text-text-secondary hover:text-primary transition-colors"
          >
            {product?.category?.name}
          </LocalePath>
          <span className="text-text-secondary">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              strokeLinecap="round"
              strokeLinejoin="round"
              className="lucide lucide-chevron-left"
            >
              <path d="m15 18-6-6 6-6"></path>
            </svg>
          </span>
          <span className="text-primary">{product?.name}</span>
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8 lg:gap-16">
          <div>
            <div className="sticky top-24">
              <div className="relative overflow-hidden rounded-3xl bg-gradient-to-br from-[#FFF5F8] to-[#F5F1ED] cursor-pointer group">
                <Fancybox options={{}}>
                  <div className="aspect-square relative">
                    <a
                      href={product?.image}
                      data-fancybox="gallery"
                      data-caption={product?.name}
                    >
                      <MediaWithFallback
                        src={product?.image}
                        alt={product?.name}
                        className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-110"
                      />
                      <div className="absolute inset-0 bg-gradient-to-t from-black/30 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                      <div className="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                        <div className="bg-white/95 backdrop-blur-sm px-6 py-3 rounded-full shadow-xl">
                          <span className="text-sm text-text-primary">
                            {t("Text.press_to_zoom")}
                          </span>
                        </div>
                      </div>
                    </a>
                  </div>
                </Fancybox>
              </div>
            </div>
          </div>
          <div className="space-y-6">
            <LocalePath
              href={`/products?category_id=${product?.category?.id}`}
              className="inline-flex items-center gap-2 px-4 py-2 bg-gradient-to-r from-primary/10 to-secondary/10 text-primary rounded-full border border-primary/20 hover:border-primary/40 transition-all duration-300"
            >
              <span className="text-sm"> {product?.category?.name}</span>
              <span className="text-xs">
                <svg
                  xmlns="http://www.w3.org/2000/svg"
                  width="14"
                  height="14"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  className="lucide lucide-chevron-left"
                >
                  <path d="m15 18-6-6 6-6"></path>
                </svg>
              </span>
            </LocalePath>
            <h1 className="text-4xl md:text-5xl cursor-pointer">
              {product?.name}
            </h1>
            <div className="flex items-center gap-2 mb-6">
              <RS className="size-6 *:fill-text-primary" />
              <span className="text-4xl text-text-primary tracking-tight">
                {product?.price}
              </span>
            </div>
            <div className="py-6 border-y border-gray-200">
              <h3 className="text-xl mb-3 text-primary">
                {t("LABELS.description")}
              </h3>
              <p className="text-text-secondary leading-relaxed text-lg">
                {product?.description}
              </p>
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div className="p-5 bg-gradient-to-br from-white to-[#FEFBF9] rounded-2xl border border-gray-200 hover:border-primary/30 transition-all duration-300">
                <p className="text-sm text-text-secondary mb-2">
                  {t("Text.flower_type")}
                </p>
                <p className="flex items-center gap-2 text-text-primary">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="18"
                    height="18"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="lucide lucide-check *:stroke-success"
                  >
                    <path d="M20 6 9 17l-5-5"></path>
                  </svg>
                  <span>{product?.category?.name}</span>
                </p>
              </div>
              <div className="p-5 bg-gradient-to-br from-white to-[#FEFBF9] rounded-2xl border border-gray-200 hover:border-primary/30 transition-all duration-300">
                <p className="text-sm text-text-secondary mb-2">
                  {t("Text.preservation_period")}
                </p>
                <p className="flex items-center gap-2 text-text-primary">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="18"
                    height="18"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="lucide lucide-check *:stroke-success"
                  >
                    <path d="M20 6 9 17l-5-5"></path>
                  </svg>
                  <span>{product?.flower_age_from}</span>
                  <span>-</span>
                  <span>{product?.flower_age_to}</span>
                  <span>{t("Text.days")}</span>
                </p>
              </div>
            </div>
            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)}>
                <div className="space-y-3">
                  <label className="block text-lg">
                    {t("validations.Quantity")}
                  </label>
                  <QuantityControl
                    initialCount={initialCount}
                    setInitialCount={setInitialCount}
                    setValue={setValue}
                    className="!w-full flex justify-between sm:!w-max !rounded-2xl !border-2 border-primary/20 !bg-white"
                  />
                </div>
                <div className="flex gap-4 pt-4">
                  <button
                    type="submit"
                    onClick={() => onSubmit(product)}
                    disabled={addToCartLoading}
                    className="flex-1 py-4 rounded-2xl font-medium text-lg transition-all duration-300 flex items-center justify-center gap-3 bg-gradient-to-r from-primary to-primary-dark hover:from-primary-dark hover:to-primary text-white shadow-xl shadow-primary/30"
                  >
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="22"
                      height="22"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      className="lucide lucide-shopping-cart"
                    >
                      <circle cx="8" cy="21" r="1"></circle>
                      <circle cx="19" cy="21" r="1"></circle>
                      <path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"></path>
                    </svg>

                    <span>{t("BUTTONS.addToCart")}</span>
                  </button>
                  <div className="relative">
                    <button
                      onClick={() => setModalOpen(!modalOpen)}
                      type="button"
                      className="w-16 h-16 border-2 border-primary/20 rounded-2xl hover:bg-primary/10 transition-all duration-300 flex items-center justify-center bg-white"
                    >
                      {!modalOpen ? (
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          width="24"
                          height="24"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          className="lucide lucide-share2 lucide-share-2 text-primary"
                        >
                          <circle cx="18" cy="5" r="3"></circle>
                          <circle cx="6" cy="12" r="3"></circle>
                          <circle cx="18" cy="19" r="3"></circle>
                          <line
                            x1="8.59"
                            x2="15.42"
                            y1="13.51"
                            y2="17.49"
                          ></line>
                          <line
                            x1="15.41"
                            x2="8.59"
                            y1="6.51"
                            y2="10.49"
                          ></line>
                        </svg>
                      ) : (
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          width="24"
                          height="24"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          className="lucide lucide-x *:stroke-text-secondary"
                        >
                          <path d="M18 6 6 18"></path>
                          <path d="m6 6 12 12"></path>
                        </svg>
                      )}
                    </button>
                    {modalOpen && (
                      <>
                        <div
                          className="fixed inset-0 z-40"
                          onClick={() => setModalOpen(false)}
                        />
                        <div className="flex flex-col gap-1 absolute top-20 left-0 bg-white/98 backdrop-blur-md rounded-2xl shadow-2xl p-3 z-[60] min-w-[220px] border-2 border-primary/10 animate-in fade-in-0 zoom-in-95 duration-200">
                          <WhatsappShareButton
                            url={shareUrl}
                            title={product?.name}
                          >
                            <div className="w-48 flex items-center gap-3 px-5 py-4 rounded-xl hover:bg-gradient-to-r hover:from-green-50 hover:to-green-100 transition-all duration-200">
                              <span className="text-2xl">💬</span>
                              <span className="text-base text-text-primary">
                                {t("Text.whatsapp")}
                              </span>
                            </div>
                          </WhatsappShareButton>
                          <InstapaperShareButton
                            url={shareUrl}
                            title={product?.name}
                          >
                            <div className="w-48 flex items-center gap-3 px-5 py-4 rounded-xl hover:bg-gradient-to-r hover:from-pink-50 hover:to-purple-100 transition-all duration-200">
                              <svg
                                xmlns="http://www.w3.org/2000/svg"
                                width="20"
                                height="20"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                className="lucide lucide-twitter text-text-primary"
                              >
                                <path d="M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z"></path>
                              </svg>
                              <span className="text-base text-text-primary">
                                {t("Text.instagram")}
                              </span>
                            </div>
                          </InstapaperShareButton>
                          <FacebookShareButton
                            url={shareUrl}
                            title={product?.name}
                          >
                            <div className="w-48 flex items-center gap-3 px-5 py-4 rounded-xl hover:bg-gradient-to-r hover:from-blue-50 hover:to-blue-100 transition-all duration-200">
                              <svg
                                xmlns="http://www.w3.org/2000/svg"
                                width="20"
                                height="20"
                                viewBox="0 0 24 24"
                                fill="none"
                                stroke="currentColor"
                                strokeWidth="2"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                className="lucide lucide-facebook text-text-primary"
                              >
                                <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z"></path>
                              </svg>
                              <span className="text-base text-text-primary">
                                {t("Text.facebook")}
                              </span>
                            </div>
                          </FacebookShareButton>
                          <div className="my-2 border-t border-gray-200"></div>
                          <button
                            onClick={() => {
                              navigator.clipboard.writeText(
                                window.location.href,
                              );
                              setModalOpen(false);
                              ShowAlertMixin({
                                icon: "success",
                                title: t("Text.copied_successfully"),
                                duration: 2000,
                              });
                            }}
                            className="w-full flex items-center gap-3 px-5 py-4 rounded-xl hover:bg-gradient-to-r hover:from-primary hover:to-secondary transition-all duration-200"
                          >
                            <svg
                              xmlns="http://www.w3.org/2000/svg"
                              width="20"
                              height="20"
                              viewBox="0 0 24 24"
                              fill="none"
                              stroke="currentColor"
                              strokeWidth="2"
                              strokeLinecap="round"
                              strokeLinejoin="round"
                              className="lucide lucide-link text-text-primary"
                            >
                              <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path>
                              <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"></path>
                            </svg>
                            <span className="text-base text-text-primary">
                              {t("Text.copy_link")}
                            </span>
                          </button>
                        </div>
                      </>
                    )}
                  </div>
                </div>
              </form>
            </Form>
          </div>
        </div>
      </div>
    </>
  );
}
