"use client";
import { getToken } from "@/actions/cookies";
import postData from "@/api/post-data";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/components/ui/form";
import { Separator } from "@/components/ui/separator";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { IoStar } from "react-icons/io5";
import { z } from "zod";
import "@/app/globals.css";
import AlertWarning from "../AlertWarning";
import Rate from "../Rate";
import SelectRate from "../SelectRate";
export default function ProductDetailsTabRedesign({ product }) {
  const locale = useLocale();
  const t = useTranslations("single-product");
  return (
    <div className="container bg-white border-[1px] md:p-6 p-2 rounded-md">
      <Tabs
        defaultValue="details"
        className="w-full"
        dir={locale == "en" ? "ltr" : "rtl"}
      >
        <TabsList className="px-0 bg-transparent flex items-center gap-4 my-5 justify-center w-full rounded-none ">
          <TabsTrigger
            value="details"
            className="border-transparent duration-500 data-[state=active]:border-secondary data-[state=active]:text-secondary border-b-2 rounded-none text-2xl font-semibold uppercase hover:border-secondary"
          >
            {t("specifications")}
          </TabsTrigger>
          <TabsTrigger
            value="review"
            className="border-transparent duration-500 data-[state=active]:text-secondary data-[state=active]:border-secondary border-b-2 rounded-none text-2xl font-semibold uppercase hover:border-secondary" >
            {t("reviews")}
          </TabsTrigger>
        </TabsList>
        <TabsContent value="details">
          <div
            className="attribute-layout leading-[3rem]"
            dangerouslySetInnerHTML={{
              __html: product.description || "",
            }}
          ></div>
        </TabsContent>
        <TabsContent value="review">
          <Reviews product={product} />
        </TabsContent>
      </Tabs>
    </div>
  );
}


export const Reviews = ({ product }) => {
  const [comments, setComments] = useState(product.comments);
  const error = useTranslations("form-errors");
  const t = useTranslations("single-product");

  const form = useForm({
    resolver: zodResolver(
      z.object({
        comment: z
          .string({ errorMap: () => ({ message: error("required") }) })
          .min(1),
        stars: z
          .number({ errorMap: () => ({ message: error("required") }) })
          .min(1),
      })
    ),
    defaultValues: {
      comment: "",
      stars: 0,
    },
  });
  const {
    reset,
    formState: { isSubmitting },
  } = form;

  async function onSubmit(values) {
    const token = await getToken();
    if (!token) {
      toastError(t("login-required"));
      return;
    }
    const formData = new FormData();
    formData.append("product_id", product.id);
    formData.append("comment", values.comment);
    formData.append("stars", values.stars);
    const { error, message, data } = await postData({
      endPoint: "/product/review",
      body: formData,
    });
    if (error) {
      return toastError(message);
    }
    reset();
    toastSuccess(message);
    setComments([...comments, { ...data }]);
  }
  return (
    <div className="py-6">
      <div className="flex flex-col gap-4 ">
        {/* rating */}
        <div className="p-4  border-gray-300 rounded-md space-y-4">
          <div className="flex items-center gap-1 justify-center">
            <h3 className="text-2xl text-gray-300">
              <span className="font-medium text-black">
                {Number(product?.rate).toFixed(1)}
              </span>
              /5.0
            </h3>
            <IoStar size={22} className="text-yellow-400" />
          </div>
          <p className="text-center text-gray-400 mt-2">
            {t("rates-average")}
          </p>
        </div>
        {/* comments */}
        <div className=" max-h-96 overflow-y-auto space-y-6">
          {comments?.length > 0 ? (
            comments.map((comment) => {
              const user = comment.user;
              if (comment?.published === "1") {
                return (
                  <div key={comment.id}>
                    <div className=" px-4 mb-5 xl:mb-10 2xl:mb-14 ">
                      <div className="flex items-center gap-3 ">
                        <Avatar className="lg:w-28 lg:h-28 rounded-md">
                          <AvatarImage className="rounded-md" src={user.image} />
                          <AvatarFallback className="rounded-md text-2xl 2xl:text-4xl">
                            {user.name.slice(0, 1)}
                          </AvatarFallback>
                        </Avatar>

                        <div className="space-y-2">
                          <p className="text-gray-600 lg:text-2xl">{comment.comment}</p>
                          <div className="flex gap-2 items-center">

                            <p className="font-semibold">{user.name}</p>
                            <p className="text-xs ">
                              {comment.created_at?.split("T")[0]}
                            </p>
                            <Rate rating={comment.stars} />
                          </div>

                        </div>

                      </div>
                    </div>
                  </div>
                );
              }
              return null; // Safely handle cases where comment.published !== '1'
            })
          ) : (
            <AlertWarning text={t("no-reviews")} />
          )}
        </div>
        {/* add comment */}
        <Form {...form}>
          <form
            onSubmit={form.handleSubmit(onSubmit)}
            className="lg:col-span-4 col-span-12 space-y-4"
          >
            <div className="h-12 flex items-center flex-col justify-center">
              <h3 className="font-semibold text-xl xl:text-2xl text-center">
                {t("add")} <span className="">{t("rate")}</span>
              </h3>
              <FormField
                name="stars"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <SelectRate
                        value={field.value}
                        onChange={field.onChange}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <FormField
              name="comment"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Textarea
                      placeholder={t("your-comment")}
                      className="bg-gray-[#F5F7F9] focus-visible:ring-secondary"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <button
              disabled={isSubmitting}
              type="submit"
              className="btn  bg-black hover:bg-secondary text-white duration-200 transition-all rounded-md lg:px-14 xl:text-xl"
            >
              {isSubmitting ? (
                <div className="flex items-center gap-2">
                  <Loader2 className="w-4 h-4 animate-spin" />
                  <span>{t("submit")}</span>
                </div>
              ) : (
                <span>{t("submit")}</span>
              )}
            </button>
          </form>
        </Form>
      </div>
    </div>
  );
};
