"use client";

import { useState } from "react";
import dynamic from "next/dynamic";
import {
  Star,
  MessageSquare,
  Check,
  Loader2,
  X,
  ChevronRight,
} from "lucide-react";

const ReviewResponseModal = dynamic(() => import("./ReviewResponseModal"), {
  ssr: false,
});

const t = {
  en: {
    noReviews: "No reviews found",
    reply: "Reply",
    replied: "Replied",
    verified: "Verified",
    loadMore: "Load More",
    reviewDetails: "Review Details",
    overallRating: "Overall Rating",
    additionalComments: "Additional Comments",
    questionResponses: "Question Responses",
    noResponses: "No question responses",
    close: "Close",
    customer: "Customer",
    email: "Email",
    phone: "Phone",
    platform: "Platform",
    date: "Date",
  },
  ar: {
    noReviews: "لا توجد تقييمات",
    reply: "رد",
    replied: "تم الرد",
    verified: "موثق",
    loadMore: "تحميل المزيد",
    reviewDetails: "تفاصيل التقييم",
    overallRating: "التقييم العام",
    additionalComments: "تعليقات إضافية",
    questionResponses: "إجابات الأسئلة",
    noResponses: "لا توجد إجابات",
    close: "إغلاق",
    customer: "العميل",
    email: "البريد الإلكتروني",
    phone: "الهاتف",
    platform: "المنصة",
    date: "التاريخ",
  },
};

interface QuestionResponse {
  questionEn: string;
  questionAr?: string;
  answer: string;
  rating?: number;
}

interface Review {
  id: string;
  _id?: string;
  customerName: string;
  customerEmail?: string | null;
  customerPhone?: string | null;
  platform: string;
  rating: number;
  title: string | null;
  content: string | null;
  responseText?: string | null;
  respondedAt?: string | null;
  isVerified?: boolean;
  questionResponses?: QuestionResponse[];
  createdAt: string | number;
}

export default function ReviewsList({
  lang,
  reviews,
  loading,
  hasMore,
  onLoadMore,
  onRefresh,
}: {
  lang: string;
  reviews: Review[];
  loading: boolean;
  hasMore: boolean;
  onLoadMore: () => void;
  onRefresh: () => void;
}) {
  const isAr = lang === "ar";
  const labels = t[isAr ? "ar" : "en"];
  const [replyTarget, setReplyTarget] = useState<Review | null>(null);
  const [detailTarget, setDetailTarget] = useState<Review | null>(null);

  if (!loading && reviews.length === 0) {
    return (
      <div className="text-center py-8 text-slate-500">{labels.noReviews}</div>
    );
  }

  return (
    <div dir={isAr ? "rtl" : "ltr"}>
      <div className="space-y-3">
        {reviews.map((review) => (
          <div
            key={review.id || review._id}
            className="bg-slate-50 rounded-lg p-4 border border-slate-200 cursor-pointer hover:border-brand-green/40 transition-colors"
            onClick={() => setDetailTarget(review)}
          >
            <div className="flex items-start justify-between gap-3">
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-1 flex-wrap">
                  <span className="font-medium text-slate-900">
                    {review.customerName}
                  </span>
                  {review.isVerified && (
                    <span className="inline-flex items-center gap-1 text-xs text-green-400">
                      <Check className="w-3 h-3" />
                      {labels.verified}
                    </span>
                  )}
                  <span className="text-xs px-2 py-0.5 rounded bg-slate-200 text-slate-600">
                    {review.platform}
                  </span>
                </div>

                <div className="flex items-center gap-0.5 mb-2">
                  {[1, 2, 3, 4, 5].map((s) => (
                    <Star
                      key={s}
                      className={`w-4 h-4 ${
                        s <= review.rating
                          ? "text-yellow-400 fill-current"
                          : "text-gray-300"
                      }`}
                    />
                  ))}
                  <span className="text-xs text-slate-500 ml-2">
                    {new Date(review.createdAt).toLocaleDateString(
                      isAr ? "ar" : "en",
                    )}
                  </span>
                </div>

                {review.title && (
                  <p className="text-sm font-medium text-slate-700 mb-1">
                    {review.title}
                  </p>
                )}
                {review.content && (
                  <p className="text-sm text-slate-500 line-clamp-2">
                    {review.content}
                  </p>
                )}

                {review.responseText && (
                  <div className="mt-3 pl-3 border-l-2 border-brand-green/50">
                    <p className="text-xs text-brand-green mb-1">
                      {labels.replied}
                    </p>
                    <p className="text-sm text-slate-600">
                      {review.responseText}
                    </p>
                  </div>
                )}
              </div>

              <div className="flex items-center gap-2 shrink-0">
                {!review.responseText && (
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      setReplyTarget(review);
                    }}
                    className="flex items-center gap-1 text-xs text-brand-green hover:text-brand-green/80"
                  >
                    <MessageSquare className="w-3.5 h-3.5" />
                    {labels.reply}
                  </button>
                )}
                <ChevronRight className="w-4 h-4 text-slate-400" />
              </div>
            </div>
          </div>
        ))}
      </div>

      {hasMore && (
        <div className="text-center mt-4">
          <button
            onClick={onLoadMore}
            disabled={loading}
            className="text-sm text-brand-green hover:text-brand-green/80 disabled:opacity-50"
          >
            {loading ? (
              <Loader2 className="w-4 h-4 animate-spin inline" />
            ) : (
              labels.loadMore
            )}
          </button>
        </div>
      )}

      {/* Read-only Review Detail Modal */}
      {detailTarget && (
        <div
          className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
          onClick={() => setDetailTarget(null)}
        >
          <div
            className="bg-white rounded-xl shadow-xl w-full max-w-lg max-h-[85vh] overflow-y-auto"
            dir={isAr ? "rtl" : "ltr"}
            onClick={(e) => e.stopPropagation()}
          >
            {/* Header */}
            <div className="flex items-center justify-between p-4 border-b sticky top-0 bg-white rounded-t-xl">
              <h3 className="text-lg font-semibold text-slate-900">
                {labels.reviewDetails}
              </h3>
              <button
                onClick={() => setDetailTarget(null)}
                className="p-1 hover:bg-slate-100 rounded-lg"
              >
                <X className="w-5 h-5 text-slate-500" />
              </button>
            </div>

            <div className="p-5 space-y-5">
              {/* Customer info */}
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full bg-brand-green/10 flex items-center justify-center text-brand-green font-semibold text-lg">
                  {detailTarget.customerName.charAt(0).toUpperCase()}
                </div>
                <div>
                  <p className="font-medium text-slate-900">
                    {detailTarget.customerName}
                  </p>
                  <div className="flex items-center gap-2 text-xs text-slate-500">
                    {detailTarget.customerEmail && (
                      <span>{detailTarget.customerEmail}</span>
                    )}
                    {detailTarget.customerPhone && (
                      <span>{detailTarget.customerPhone}</span>
                    )}
                  </div>
                </div>
              </div>

              {/* Rating */}
              <div className="bg-slate-50 rounded-lg p-4">
                <p className="text-xs text-slate-500 mb-2 font-medium uppercase tracking-wide">
                  {labels.overallRating}
                </p>
                <div className="flex items-center gap-1">
                  {[1, 2, 3, 4, 5].map((s) => (
                    <Star
                      key={s}
                      className={`w-6 h-6 ${
                        s <= detailTarget.rating
                          ? "text-yellow-400 fill-current"
                          : "text-gray-300"
                      }`}
                    />
                  ))}
                  <span className="text-lg font-semibold text-slate-900 ml-2">
                    {detailTarget.rating}/5
                  </span>
                </div>
                <div className="flex items-center gap-3 mt-2 text-xs text-slate-500">
                  <span>
                    {labels.platform}: {detailTarget.platform}
                  </span>
                  <span>
                    {labels.date}:{" "}
                    {new Date(detailTarget.createdAt).toLocaleDateString(
                      isAr ? "ar" : "en",
                      { year: "numeric", month: "short", day: "numeric" },
                    )}
                  </span>
                </div>
              </div>

              {/* Additional comments */}
              {detailTarget.content && (
                <div>
                  <p className="text-xs text-slate-500 mb-2 font-medium uppercase tracking-wide">
                    {labels.additionalComments}
                  </p>
                  <p className="text-sm text-slate-700 bg-slate-50 rounded-lg p-3">
                    {detailTarget.content}
                  </p>
                </div>
              )}

              {/* Question Responses */}
              {detailTarget.questionResponses &&
                detailTarget.questionResponses.length > 0 && (
                  <div>
                    <p className="text-xs text-slate-500 mb-3 font-medium uppercase tracking-wide">
                      {labels.questionResponses}
                    </p>
                    <div className="space-y-3">
                      {detailTarget.questionResponses.map((qr, i) => (
                        <div
                          key={i}
                          className="bg-slate-50 rounded-lg p-3 border border-slate-100"
                        >
                          <p className="text-sm font-medium text-slate-700 mb-1">
                            {isAr
                              ? qr.questionAr || qr.questionEn
                              : qr.questionEn}
                          </p>
                          <p className="text-sm text-slate-600">
                            {qr.rating !== undefined
                              ? `${qr.rating}/5 — ${qr.answer}`
                              : qr.answer}
                          </p>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

              {/* Owner response */}
              {detailTarget.responseText && (
                <div className="border-l-2 border-brand-green/50 pl-3">
                  <p className="text-xs text-brand-green mb-1 font-medium">
                    {labels.replied}
                  </p>
                  <p className="text-sm text-slate-600">
                    {detailTarget.responseText}
                  </p>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {replyTarget && (
        <ReviewResponseModal
          lang={lang}
          reviewId={replyTarget.id || replyTarget._id || ""}
          customerName={replyTarget.customerName}
          onClose={() => setReplyTarget(null)}
          onSuccess={onRefresh}
        />
      )}
    </div>
  );
}
