"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 AlertWarning from "../shared/AlertWarning";
import Rate from "../shared/Rate";
import SelectRate from "../shared/SelectRate";
import "@/app/globals.css";
export default function ProductDetailsTab({ product }) {
  const locale = useLocale();
  const t = useTranslations("single-product");
  return (
    <div className="container bg-white md:p-6 p-2 rounded-md">
      <Tabs
        defaultValue="details"
        className="w-full"
        dir={locale == "en" ? "ltr" : "rtl"}
      >
        <TabsList className="px-0 bg-transparent border-b border-gray-400 rounded-none w-full justify-start">
          <TabsTrigger
            value="details"
            className="lg:px-12 md:text-base text-sm data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-main data-[state=active]:rounded-none"
          >
            {t("specifications")}
          </TabsTrigger>
          <TabsTrigger
            value="review"
            className="lg:px-12 md:text-base text-sm data-[state=active]:bg-transparent data-[state=active]:shadow-none data-[state=active]:border-b-2 data-[state=active]:border-main data-[state=active]:rounded-none"
          >
            {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>
  );
}

/**
 * Calculate the average rating from an array of comments.
 *
 * @param {Array<Comment>} comments - The array of comments to calculate the average rating from.
 * @returns {number} The average rating, rounded to one decimal place.
 */
// const calculateAverageRating = (comments) => {
//   if (comments.length === 0) return 0;
//   const totalStars = comments.reduce((acc, comment) => acc + Number(comment.stars), 0);
//   const average = totalStars / comments.length;
//   return Math.min([average], 5).toFixed(1);
// };

/**
 * A component that renders a reviews section of a product page.
 *
 * The component renders three parts: the average rating of the product, the comments
 * section, and a form to add a new comment.
 *
 * The average rating section renders the average rating of the product, rounded to one
 * decimal place, and a note that the rating is based on the number of comments.
 *
 * The comments section renders a list of comments, each of which contains the user name,
 * the date of the comment, the rating, and the comment text. If there are no comments, it
 * renders an alert warning that there are no reviews.
 *
 * The form to add a new comment renders a textarea to enter the comment, a select to enter
 * the rating, and a submit button. The form is validated using the `zod` library, and the
 * `react-hook-form` library is used to handle the form submission.
 *
 * If the user is not logged in, the form renders an alert warning that the user must be
 * logged in to add a review.
 *
 * @param {object} data - The data of the product, which contains the comments and the
 * average rating.
 * @returns {ReactElement} - The reviews component.
 */
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="grid grid-cols-12 lg:gap-10 gap-4 ">
        {/* rating */}
        <div className="lg:col-span-2 md:col-span-4 col-span-12">
          <div className="p-4 border-2 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>
        </div>
        {/* comments */}
        <div className="lg:col-span-6 md:col-span-8 col-span-12 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="space-y-4 px-4">
                      <p className="text-xs text-end">
                        {comment.created_at?.split("T")[0]}
                      </p>
                      <div className="flex items-center gap-1">
                        <Avatar>
                          <AvatarImage src={user.image} />
                          <AvatarFallback>
                            {user.name.slice(0, 1)}
                          </AvatarFallback>
                        </Avatar>
                        <div>
                          <p className="font-semibold">{user.name}</p>
                          <Rate rating={comment.stars} />
                        </div>
                      </div>
                      <p>{comment.comment}</p>
                    </div>
                    <Separator className="my-4" />
                  </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"
          >
            <h3 className="font-semibold text-xl">
              {t("add")} <span className="text-main">{t("rate")}</span>
            </h3>
            <FormField
              name="comment"
              control={form.control}
              render={({ field }) => (
                <FormItem>
                  <FormControl>
                    <Textarea
                      placeholder={t("your-comment")}
                      className="bg-gray-[#F5F7F9] focus-visible:ring-main"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
            <div className="h-12">
              <FormField
                name="stars"
                control={form.control}
                render={({ field }) => (
                  <FormItem>
                    <FormControl>
                      <SelectRate
                        value={field.value}
                        onChange={field.onChange}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>
            <button
              disabled={isSubmitting}
              type="submit"
              className="btn btn-main rounded-none"
            >
              {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>
  );
};
