"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import Modal from "@/components/elements/Modal";
import IOSSpinner from "@/components/ui/IOSSpinner";
import { IMAGE_BASE_URL, staticIconUrl } from "@/components/main/BaseUrl";
import useAxios from "@/hooks/useAxios";
import { useRequireAuth } from "@/lib/auth/useRequireAuth";
import { btnPrimary } from "@/lib/ui/buttonStyles";
import { cn } from "@/lib/utils";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";

type ProductComment = {
  _id: string;
  comment: string;
  rating?: number | null;
  createdAt: string;
  creator: {
    _id: string;
    user_name: string;
    profile_image?: string;
  };
};

type ShopProductCommentsModalProps = {
  open: boolean;
  onClose: () => void;
  listingId: string;
};

export default function ShopProductCommentsModal({
  open,
  onClose,
  listingId,
}: ShopProductCommentsModalProps) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const requireAuth = useRequireAuth();

  const [comments, setComments] = useState<ProductComment[] | null>(null);
  const [hasRated, setHasRated] = useState(false);
  const [text, setText] = useState("");
  const [rate, setRate] = useState(0);
  const [sending, setSending] = useState(false);

  const loadComments = () => {
    setComments(null);
    request<{ docs: ProductComment[]; hasRated?: boolean }>(
      "GET",
      `/shop-products/${listingId}/comments`,
      null,
      { noToast: true }
    )
      .then((res) => {
        setComments(res?.docs || []);
        setHasRated(Boolean(res?.hasRated));
      })
      .catch(() => setComments([]));
  };

  useEffect(() => {
    if (open && listingId) {
      loadComments();
      setRate(0);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, listingId]);

  const handleSubmit = async () => {
    if (!requireAuth() || !text.trim() || sending) return;
    setSending(true);
    try {
      const res = await request<{ comment: ProductComment }>(
        "POST",
        `/shop-products/${listingId}/comments`,
        rate > 0 ? { comment: text.trim(), rate } : { comment: text.trim() }
      );
      if (res?.comment) {
        setComments((prev) => [res.comment, ...(prev || [])]);
        if (rate > 0) setHasRated(true);
      }
      setText("");
      setRate(0);
    } catch {
      toast.error(t("posts.commentError"));
    } finally {
      setSending(false);
    }
  };

  return (
    <Modal isOpen={open} onClose={onClose} height="min(82vh, 520px)">
      <div className="flex h-full flex-col">
        <h3 className="mb-3 shrink-0 text-center text-sm font-bold">
          {t("posts.comments")}
        </h3>

        <div className="flex-1 overflow-y-auto px-1">
          {comments === null ? (
            <div className="flex justify-center py-8">
              <IOSSpinner />
            </div>
          ) : comments.length === 0 ? (
            <p className="py-8 text-center text-sm text-neutral-500">
              {t("posts.noComments")}
            </p>
          ) : (
            <ul className="space-y-3">
              {comments.map((c) => (
                <li key={c._id} className="flex items-start gap-3">
                  <div className="relative h-9 w-9 shrink-0 overflow-hidden rounded-full bg-neutral-200 dark:bg-neutral-800">
                    {c.creator?.profile_image ? (
                      <Image
                        src={IMAGE_BASE_URL + c.creator.profile_image}
                        alt=""
                        fill
                        className="object-cover"
                        unoptimized
                      />
                    ) : null}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-1.5">
                      <p className="text-xs font-semibold">{c.creator?.user_name}</p>
                      {c.rating ? (
                        <span className="flex items-center gap-0.5 text-[10px] font-bold text-amber-500">
                          {c.rating}
                          <Image
                            src={staticIconUrl("/images/icons/star1.png")}
                            alt=""
                            width={12}
                            height={12}
                          />
                        </span>
                      ) : null}
                    </div>
                    <p className="break-words text-sm text-neutral-700 dark:text-neutral-300">
                      {c.comment}
                    </p>
                  </div>
                </li>
              ))}
            </ul>
          )}
        </div>

        <div className="mt-3 shrink-0 border-t border-neutral-200 pt-3 dark:border-neutral-700">
          {!hasRated && (
            <div className="mb-2 flex items-center justify-center gap-1">
              {[1, 2, 3, 4, 5].map((n) => (
                <button
                  key={n}
                  type="button"
                  onClick={() => setRate(n === rate ? 0 : n)}
                  aria-label={t("posts.ratingOptional")}
                  className="p-0.5"
                >
                  <Image
                    src={staticIconUrl("/images/icons/star1.png")}
                    alt=""
                    width={20}
                    height={20}
                    className={n <= rate ? "opacity-100" : "opacity-30"}
                  />
                </button>
              ))}
            </div>
          )}
          <div className="flex items-center gap-2">
            <input
              type="text"
              value={text}
              onChange={(e) => setText(e.target.value)}
              placeholder={t("posts.writeComment")}
              className="flex-1 rounded-full border border-neutral-300 bg-transparent px-4 py-2 text-sm outline-none dark:border-neutral-600"
            />
            <button
              type="button"
              disabled={!text.trim() || sending}
              onClick={() => void handleSubmit()}
              className={cn(btnPrimary, "shrink-0 rounded-full px-4 py-2 text-xs font-bold disabled:opacity-40")}
            >
              {t("posts.send")}
            </button>
          </div>
        </div>
      </div>
    </Modal>
  );
}
