// productdetails/components/ProductAccordion.tsx
"use client";

import React, { useEffect, useState } from "react";
import { apiCall } from "@/utils/callApi";
import { toast } from "sonner";

interface ProductAccordionProps {
  description?: string;
  reviews?: any[];
  weight?: number;
  dimensions?: any;
  productId: string;
}

export default function ProductAccordion({
  description,
  reviews,
  weight,
  dimensions,
  productId,
}: ProductAccordionProps) {
  const [openAccordion, setOpenAccordion] = useState<number | null>(null);
  const [rating, setRating] = useState<number>(0);
  const [hoverRating, setHoverRating] = useState<number>(0);
  const toggleAccordion = (index: number) => {
    setOpenAccordion(openAccordion === index ? null : index);
  };

  return (
    <div className="dltaccordion">
      {/* Product Details Accordion */}
      <div className="dltaccordionitem">
        <button
          onClick={() => toggleAccordion(1)}
          className="dltaccordionheader flex w-full items-center justify-between"
        >
          <span className="flex items-center gap-2">
            <svg viewBox="0 0 19 21" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M17.4679 12.94L12.5693 8.04L13.0576 6.17417C13.2449 5.3125 13.3398 4.43083 13.3398 3.55333V0.666667C13.3398 0.436667 13.1565 0.25 12.9308 0.25C12.705 0.25 12.5218 0.436667 12.5218 0.666667V2.78C11.0168 2.925 9.78667 3.81583 9.25011 4.27417C8.71354 3.81583 7.48338 2.925 5.97838 2.78V0.666667C5.97838 0.436667 5.79516 0.25 5.56942 0.25C5.34367 0.25 5.16045 0.436667 5.16045 0.666667V3.5525C5.16045 4.43417 5.25533 5.31583 5.44673 6.19083L5.93094 8.03917L1.0528 12.9192C0.167798 13.6858 -0.00969338 14.9975 0.64138 15.97C2.35167 18.53 5.81071 20.25 9.24929 20.25C12.6879 20.25 16.1477 18.5308 17.8572 15.97C18.5083 14.9975 18.3308 13.6858 17.467 12.9392L17.4679 12.94ZM9.24929 5.25C9.35398 5.25 9.45868 5.21 9.53884 5.12833C9.55274 5.11417 10.8647 3.82333 12.5177 3.62333C12.5128 4.4175 12.4278 5.21417 12.2625 5.97583L11.798 7.74917H6.70143L6.24094 5.9925C6.07162 5.21667 5.98656 4.42 5.98165 3.6225C7.63469 3.82167 8.94665 5.11333 8.96056 5.1275C9.04072 5.20833 9.14541 5.24917 9.25011 5.24917L9.24929 5.25ZM17.1816 15.5017C15.6406 17.8075 12.3787 19.4167 9.24929 19.4167C6.11988 19.4167 2.85797 17.8067 1.31699 15.5017C0.9023 14.8817 1.01681 14.045 1.6049 13.5342L6.5542 8.58417H11.946L16.9166 13.555C17.4826 14.0458 17.5971 14.8825 17.1824 15.5025L17.1816 15.5017Z" fill="currentColor" stroke="currentColor" stroke-width="0.5"></path>
            </svg>
            <span>Product Details</span>
          </span>

          <span
            className={`transition-transform duration-300 ${
              openAccordion === 1 ? "rotate-180" : ""
            }`}
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 16 16"
              fill="currentColor"
              className="h-4 w-4"
            >
              <path d="M8.75 3.75a.75.75 0 0 0-1.5 0v3.5h-3.5a.75.75 0 0 0 0 1.5h3.5v3.5a.75.75 0 0 0 1.5 0v-3.5h3.5a.75.75 0 0 0 0-1.5h-3.5v-3.5Z" />
            </svg>
          </span>
        </button>

        {openAccordion === 1 && (
          <div className="dltaccordionbody transition-all duration-300 ease-in-out">
            <div className="pb-5 text-sm text-slate-500">
              <div className="-mx-3 flex flex-wrap">
                {weight && (
                  <div className="mb-3 w-6/12 px-3 2xl:mb-5">
                    <h4>Weight</h4>
                    <p>{weight} g</p>
                  </div>
                )}

                {dimensions && (
                  <div className="mb-3 w-6/12 px-3 2xl:mb-5">
                    <h4>Dimensions</h4>
                    <p>
                      {dimensions.length} x {dimensions.width} x{" "}
                      {dimensions.height} cm
                    </p>
                  </div>
                )}

                {description && (
                  <div className="mb-3 w-full px-3 2xl:mb-5">
                    <h4>Description</h4>

                    <div dangerouslySetInnerHTML={{ __html: description }} />
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Reviews Accordion */}
      <div className="dltaccordionitem">
        <button
          onClick={() => toggleAccordion(2)}
          className="dltaccordionheader flex w-full items-center justify-between"
        >
          <span className="flex items-center gap-2">
            <svg viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M7.72222 20.2502H3.58395C2.69973 20.2502 1.85173 19.8991 1.22649 19.2739C0.601255 18.6488 0.25 17.801 0.25 16.9169V12.7502C0.25 11.8662 0.601255 11.0183 1.22649 10.3932C1.85173 9.7681 2.69973 9.41691 3.58395 9.41691H10.9662C11.4172 9.41712 11.8606 9.53376 12.2534 9.75552C12.6462 9.97727 12.9751 10.2967 13.2082 10.6827L15.8896 7.73691C16.1114 7.49307 16.379 7.29532 16.6773 7.15496C16.9756 7.01461 17.2986 6.9344 17.6279 6.91892C17.9571 6.90344 18.2863 6.95299 18.5964 7.06475C18.9065 7.17651 19.1915 7.34828 19.4352 7.57024C19.9215 8.01685 20.2129 8.63649 20.2467 9.29576C20.2805 9.95504 20.0541 10.6012 19.6161 11.0952L13.9484 17.4594C13.1658 18.3369 12.2066 19.0392 11.1336 19.5201C10.0606 20.0011 8.89811 20.2499 7.72222 20.2502ZM3.58395 11.0836C3.14184 11.0836 2.71784 11.2592 2.40522 11.5717C2.0926 11.8843 1.91698 12.3082 1.91698 12.7502V16.9169C1.91698 17.3589 2.0926 17.7829 2.40522 18.0954C2.71784 18.408 3.14184 18.5836 3.58395 18.5836H7.72222C8.66233 18.5832 9.59175 18.3842 10.4496 17.9996C11.3074 17.615 12.0742 17.0535 12.6998 16.3519L18.3717 9.98691C18.519 9.82107 18.5952 9.60404 18.584 9.38256C18.5727 9.16107 18.475 8.95285 18.3117 8.80274C18.1457 8.65351 17.928 8.57489 17.7049 8.58358C17.5943 8.58825 17.4858 8.61491 17.3856 8.66198C17.2854 8.70905 17.1956 8.7756 17.1215 8.85775L13.4325 12.9169C13.2705 13.3651 12.9899 13.7608 12.6205 14.062C12.2512 14.3631 11.807 14.5584 11.3354 14.6269L7.03376 15.2419C6.81492 15.2733 6.59257 15.2165 6.41563 15.084C6.23868 14.9514 6.12164 14.754 6.09025 14.5352C6.05886 14.3164 6.1157 14.0941 6.24825 13.9172C6.3808 13.7403 6.57821 13.6233 6.79705 13.5919L11.0995 12.9777C11.3383 12.9444 11.5556 12.8216 11.7074 12.6342C11.8592 12.4469 11.9342 12.2089 11.9172 11.9684C11.9003 11.7279 11.7927 11.5028 11.6162 11.3386C11.4396 11.1743 11.2073 11.0832 10.9662 11.0836H3.58395ZM9.41837 7.81191C9.0406 7.81293 8.67385 7.68472 8.37901 7.44858C6.95208 6.30358 5.25093 4.58358 5.25093 2.91691C5.23047 2.23222 5.48204 1.56728 5.95063 1.06755C6.41922 0.567814 7.06668 0.273954 7.7514 0.250244C8.3743 0.25267 8.97193 0.496759 9.41837 0.931077C9.86481 0.496759 10.4625 0.25267 11.0854 0.250244C11.7701 0.273954 12.4175 0.567814 12.8861 1.06755C13.3547 1.56728 13.6063 2.23222 13.5858 2.91691C13.5858 4.58358 11.8847 6.30358 10.4569 7.44941C10.1622 7.68507 9.79576 7.81297 9.41837 7.81191ZM7.7514 1.91691C7.50914 1.94121 7.2861 2.05959 7.13024 2.2466C6.97437 2.4336 6.89813 2.67429 6.91791 2.91691C6.91791 3.66691 7.87725 4.90858 9.42337 6.14941C10.9595 4.90858 11.9188 3.66691 11.9188 2.91691C11.9386 2.67429 11.8624 2.4336 11.7065 2.2466C11.5506 2.05959 11.3276 1.94121 11.0854 1.91691C10.8431 1.94121 10.6201 2.05959 10.4642 2.2466C10.3083 2.4336 10.2321 2.67429 10.2519 2.91691C10.2519 3.13792 10.164 3.34989 10.0077 3.50617C9.85143 3.66245 9.63943 3.75024 9.41837 3.75024C9.19732 3.75024 8.98532 3.66245 8.82901 3.50617C8.6727 3.34989 8.58488 3.13792 8.58488 2.91691C8.60466 2.67429 8.52842 2.4336 8.37255 2.2466C8.21669 2.05959 7.99365 1.94121 7.7514 1.91691Z" fill="currentColor" stroke="white" stroke-width="0.5"></path>
            </svg>
            <span>Reviews ({reviews?.length || 0})</span>
          </span>

          <span
            className={`transition-transform duration-300 ${
              openAccordion === 2 ? "rotate-180" : ""
            }`}
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              viewBox="0 0 16 16"
              fill="currentColor"
              className="h-4 w-4"
            >
              <path d="M8.75 3.75a.75.75 0 0 0-1.5 0v3.5h-3.5a.75.75 0 0 0 0 1.5h3.5v3.5a.75.75 0 0 0 1.5 0v-3.5h3.5a.75.75 0 0 0 0-1.5h-3.5v-3.5Z" />
            </svg>
          </span>
        </button>

        {openAccordion === 2 && (
          <div className="dltaccordionbody transition-all duration-300 ease-in-out">
            <div className="pb-5">
              {reviews && reviews.length > 0 ? (
                <ReviewsList reviews={reviews} productId={productId} />
              ) : (
                <div className="py-8 text-center">
                  <p className="text-gray-500">
                    No reviews yet. Be the first to review this product!
                  </p>
                </div>
              )}

              <ReviewForm productId={productId} />
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

function ReviewsList({
  reviews,
  productId,
}: {
  reviews: any[];
  productId: string;
}) {
  const getInitials = (name: string) => {
    if (!name) return "?";

    return name.charAt(0).toUpperCase();
  };

  const getAvatarColor = (name: string) => {
    const colors = [
      "#FF6B6B",
      "#4ECDC4",
      "#45B7D1",
      "#96CEB4",
      "#FFEAA7",
      "#DDA16B",
      "#C44569",
      "#786FA6",
      "#F8A5C2",
      "#63CDDA",
      "#EA868F",
      "#6C5CE7",
      "#00CEC9",
      "#FFB8B8",
      "#85C1E9",
    ];

    let hash = 0;

    for (let i = 0; i < name.length; i++) {
      hash = name.charCodeAt(i) + ((hash << 5) - hash);
    }

    const index = Math.abs(hash) % colors.length;

    return colors[index];
  };

  return (
    <div className="ratingouter">
      {reviews.map((review) => (
        <div className="reviewslistbx mb-4 flex" key={review._id}>
          <div className="reviewsuserimg flex-shrink-0">
            <div
              className="flex h-12 w-12 items-center justify-center rounded-full text-xl font-bold uppercase text-white"
              style={{
                backgroundColor: getAvatarColor(review.authorName),
              }}
            >
              {getInitials(review.authorName)}
            </div>
          </div>

          <div className="reviewsuserct flex-1">
            <h6 className="text-base font-semibold">{review.authorName}</h6>

            <div className="rating mb-2 flex gap-1">
              {[...Array(5)].map((_, i) => (
                <i
                  key={i}
                  className={`fa ${
                    i < review.rating ? "fa-star" : "fa-star-o"
                  } text-yellow-400`}
                ></i>
              ))}
            </div>

            {review.reviewTitle && (
              <h5 className="mb-1 font-semibold text-gray-800">
                {review.reviewTitle}
              </h5>
            )}

            <p
              dangerouslySetInnerHTML={{
                __html: review.reviewDescription,
              }}
            />
            <p>
            <small className="text-gray-400">
              {new Date(review.createdAt).toLocaleDateString("en-IN", {
                year: "numeric",
                month: "long",
                day: "numeric",
              })}
            </small>
            </p>
          </div>
        </div>
      ))}
    </div>
  );
}

function ReviewForm({ productId }: { productId: string }) {
  const [rating, setRating] = useState(0);
  const [hoverRating, setHoverRating] = useState(0);

  const [formData, setFormData] = useState({
    authorName: "",
    authorEmail: "",
    reviewTitle: "",
    reviewDescription: "",
  });

  const [errors, setErrors] = useState<any>({});
  const [loading, setLoading] = useState(false);
  const [successMessage, setSuccessMessage] = useState("");

  const checkValidation = (key: string, value: string) => {
    let error: string | null = null;

    switch (key) {
      case "authorName":
        const usernameRegex = /^[A-Za-z][A-Za-z ]{1,49}$/;

        if (value.length < 2 || value.length > 50) {
          error = "Username must be 2–50 characters";
        } else if (!usernameRegex.test(value)) {
          error = "Name must start with a letter and contain only letters";
        }
        break;

      case "reviewTitle":
        const titleRegex = /^[A-Za-z0-9\s.,!?'"()\-:&%₹⭐]+$/;
        if (!titleRegex.test(value)) {
          error = "Title contains invalid characters";
        }

        if (value.length < 3 || value.length > 100) {
          error = "Title must be 3-100 characters";
        }
        break;

      case "reviewDescription":
        if (value?.trim()?.length < 20) {
          error = "Description must be at of 20 characters";
        } else if (value?.trim()?.length > 1000) {
          error = "Description must be less than 1000 characters";
        }
        break;

      case "authorEmail":
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        if (!emailRegex.test(value)) {
          error = "Invalid email address";
        }
        break;

      default:
        error = null;
    }

    setErrors((prev: any) => ({
      ...prev,
      [key]: error,
    }));

    return error;
  };

  const handleSubmit = async () => {
    const { authorName, authorEmail, reviewTitle, reviewDescription } =
      formData;

    if (!authorName || !authorEmail || !reviewTitle || !reviewDescription) {
      toast.error("Required fields are empty");
      return;
    }

    if (rating < 1 || rating > 5) {
      toast.error("Please select a rating");
      return;
    }

    const nameInvalid = checkValidation("authorName", authorName);

    if (nameInvalid) {
      toast.error(nameInvalid);
      return;
    }

    const emailInvalid = checkValidation("authorEmail", authorEmail);

    if (emailInvalid) {
      toast.error(emailInvalid);
      return;
    }

    const titleInvalid = checkValidation("reviewTitle", reviewTitle);

    if (titleInvalid) {
      toast.error(titleInvalid);
      return;
    }

    const descInvalid = checkValidation("reviewDescription", reviewDescription);

    if (descInvalid) {
      toast.error(descInvalid);
      return;
    }

    try {
      setLoading(true);

      const payload = {
        product: productId,
        authorName,
        authorEmail,
        reviewTitle,
        reviewDescription,
        rating: Number(rating),
      };

      // console.log("Submitting Review:", payload);

      const response = await apiCall<any>("/clientapi/addreview", {
        method: "POST",
        body: payload,
      });

      if (response?.data?.success) {
        toast.success("Thank you for your review");

        setFormData({
          authorName: "",
          authorEmail: "",
          reviewTitle: "",
          reviewDescription: "",
        });

        // Reset stars
        setRating(0);
        setHoverRating(0);

        setErrors({});
        setSuccessMessage("");
      } else {
        toast.error(
          response?.error || response?.data?.message || "Something went wrong",
        );
      }
    } catch (error) {
      console.error(error);
      toast.error("Something went wrong");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="reviewformbx mt-6">
      <h3>Add Reviews</h3>

      {successMessage && (
        <div className="mb-4 rounded bg-green-100 p-3 text-green-700">
          {successMessage}
        </div>
      )}

      <div className="revarea mb-4">
        <label className="control-label">Your Rating :</label>

        <div className="rating-area">
          <div className="starpanel flex gap-1">
            {[1, 2, 3, 4, 5].map((star) => (
              <span
                key={star}
                onClick={() => setRating(star)}
                onMouseEnter={() => setHoverRating(star)}
                onMouseLeave={() => setHoverRating(0)}
                className={`cursor-pointer text-3xl transition-colors ${
                  star <= (hoverRating || rating)
                    ? "text-yellow-400"
                    : "text-gray-300"
                }`}
              >
                ★
              </span>
            ))}
          </div>
        </div>
      </div>

      <div className="p-0">
        <div className="row">
          <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
            <div className="form-group mb-3">
              <label className="mb-1 block">Name *</label>

              <input
                type="text"
                value={formData.authorName}
                onChange={(e) => {
                  setFormData({
                    ...formData,
                    authorName: e.target.value,
                  });
                  checkValidation("authorName", e.target.value);
                }}
                className="form-control w-full rounded-md border p-2"
              />
              <div className="ml-3">
                {errors.authorName && (
                  <span className="mt-1 text-sm text-red-500">
                    {errors.authorName}
                  </span>
                )}
              </div>
            </div>
          </div>

          <div className="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
            <div className="form-group mb-3">
              <label className="mb-1 block">Email *</label>

              <input
                type="email"
                value={formData.authorEmail}
                onChange={(e) => {
                  setFormData({
                    ...formData,
                    authorEmail: e.target.value,
                  });
                  checkValidation("authorEmail", e.target.value);
                }}
                className="form-control w-full rounded-md border p-2"
              />

              {errors.authorEmail && (
                <span className="mt-1 text-sm text-red-500">
                  {errors.authorEmail}
                </span>
              )}
            </div>
          </div>

          <div className="col-12">
            <div className="form-group mb-3">
              <label className="mb-1 block">Review Title *</label>

              <input
                type="text"
                value={formData.reviewTitle}
                onChange={(e) => {
                  setFormData({
                    ...formData,
                    reviewTitle: e.target.value,
                  });
                  checkValidation("reviewTitle", e.target.value);
                }}
                className="form-control w-full rounded-md border p-2"
              />

              {errors.reviewTitle && (
                <span className="mt-1 text-sm text-red-500">
                  {errors.reviewTitle}
                </span>
              )}
            </div>
          </div>

          <div className="col-12">
            <div className="form-group mb-3">
              <label className="mb-1 block">Your Review *</label>

              <textarea
                rows={4}
                value={formData.reviewDescription}
                onChange={(e) => {
                  setFormData({
                    ...formData,
                    reviewDescription: e.target.value,
                  });
                  checkValidation("reviewDescription", e.target.value);
                }}
                className="form-control w-full rounded-md border p-2"
              />

              {errors.reviewDescription && (
                <span className="mt-1 text-sm text-red-500">
                  {errors.reviewDescription}
                </span>
              )}
            </div>
          </div>
        </div>

        <div className="row">
          <div className="col-12">
            <button
              className="theme-btn"
              type="button"
              disabled={loading}
              onClick={handleSubmit}
            >
              {loading ? "Submitting..." : "Submit Your Review"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
