"use client";

import { useState, useEffect, useCallback } from "react";
import dynamic from "next/dynamic";
import {
  Star,
  Send,
  Users,
  Plus,
  Loader2,
  Lock,
  RefreshCw,
  Award,
  ListChecks,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";

const ReviewsList = dynamic(() => import("./ReviewsList"), { ssr: false });
const ReviewStats = dynamic(() => import("./ReviewStats"), { ssr: false });
const ReviewRequestForm = dynamic(() => import("./ReviewRequestForm"), {
  ssr: false,
});
const ReferralsList = dynamic(() => import("./ReferralsList"), { ssr: false });
const ReferralStats = dynamic(() => import("./ReferralStats"), { ssr: false });
const ReferralForm = dynamic(() => import("./ReferralForm"), { ssr: false });
const TestimonialsList = dynamic(() => import("./TestimonialsList"), {
  ssr: false,
});
const TestimonialsSettings = dynamic(() => import("./TestimonialsSettings"), {
  ssr: false,
});
const ReviewRequestsList = dynamic(() => import("./ReviewRequestsList"), {
  ssr: false,
});
const BulkReviewRequestModal = dynamic(
  () => import("./BulkReviewRequestModal"),
  { ssr: false },
);
const ReviewQuestionEditor = dynamic(() => import("./ReviewQuestionEditor"), {
  ssr: false,
});

const t = {
  en: {
    title: "Reviews & Referrals",
    reviews: "Reviews",
    requests: "Requests",
    testimonials: "Testimonials",
    referrals: "Referrals",
    addReview: "Add Review",
    requestReview: "Request Review",
    bulkRequest: "Bulk Request",
    createCode: "Create Code",
    refresh: "Refresh",
    upgrade: "Upgrade to access Reviews & Referrals",
    upgradeDesc:
      "Collect customer reviews, send review requests, and manage referral programs to grow your business.",
    upgradeBtn: "Upgrade Plan",
    loading: "Loading...",
  },
  ar: {
    title: "التقييمات والإحالات",
    reviews: "التقييمات",
    requests: "الطلبات",
    testimonials: "الشهادات",
    referrals: "الإحالات",
    addReview: "إضافة تقييم",
    requestReview: "طلب تقييم",
    bulkRequest: "طلب جماعي",
    createCode: "إنشاء رمز",
    refresh: "تحديث",
    upgrade: "قم بالترقية للوصول إلى التقييمات والإحالات",
    upgradeDesc:
      "اجمع تقييمات العملاء، أرسل طلبات التقييم، وأدر برامج الإحالة لتنمية عملك.",
    upgradeBtn: "ترقية الخطة",
    loading: "جاري التحميل...",
  },
};

type SubTab = "reviews" | "requests" | "testimonials" | "referrals";

// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ReviewItem = any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ReferralItem = any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ReviewStatsType = any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ReferralStatsType = any;

interface ReviewsPanelProps {
  lang: string;
  hasAccess: boolean;
  userId?: string;
}

export default function ReviewsPanel({
  lang,
  hasAccess,
  userId,
}: ReviewsPanelProps) {
  const isAr = lang === "ar";
  const labels = t[isAr ? "ar" : "en"];

  const [subTab, setSubTab] = useState<SubTab>("reviews");
  const [reviews, setReviews] = useState<ReviewItem[]>([]);
  const [referrals, setReferrals] = useState<ReferralItem[]>([]);
  const [reviewStats, setReviewStats] = useState<ReviewStatsType>(null);
  const [referralStats, setReferralStats] = useState<ReferralStatsType>(null);
  const [reviewPage, setReviewPage] = useState(1);
  const [referralPage, setReferralPage] = useState(1);
  const [reviewTotal, setReviewTotal] = useState(0);
  const [referralTotal, setReferralTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [showRequestForm, setShowRequestForm] = useState(false);
  const [showReferralForm, setShowReferralForm] = useState(false);
  const [showBulkRequest, setShowBulkRequest] = useState(false);
  const [requestRefresh, setRequestRefresh] = useState(0);

  const fetchReviews = useCallback(async (page = 1, append = false) => {
    setLoading(true);
    try {
      const res = await fetchWithCSRF(
        `/api/dashboard/reviews?page=${page}&limit=20`,
      );
      if (res.ok) {
        const data = await res.json();
        if (append) {
          setReviews((prev) => [...prev, ...(data.reviews ?? [])]);
        } else {
          setReviews(data.reviews ?? []);
        }
        setReviewTotal(data.total ?? 0);
        setReviewPage(page);
      }
    } catch {
      /* ignore */
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchReferrals = useCallback(async (page = 1, append = false) => {
    setLoading(true);
    try {
      const res = await fetchWithCSRF(
        `/api/dashboard/referrals?page=${page}&limit=20`,
      );
      if (res.ok) {
        const data = await res.json();
        if (append) {
          setReferrals((prev) => [...prev, ...(data.referrals ?? [])]);
        } else {
          setReferrals(data.referrals ?? []);
        }
        setReferralTotal(data.total ?? 0);
        setReferralPage(page);
      }
    } catch {
      /* ignore */
    } finally {
      setLoading(false);
    }
  }, []);

  const fetchStats = useCallback(async () => {
    try {
      const [revRes, refRes] = await Promise.all([
        fetchWithCSRF("/api/dashboard/reviews/stats"),
        fetchWithCSRF("/api/dashboard/referrals/stats"),
      ]);
      if (revRes.ok) {
        const data = await revRes.json();
        setReviewStats(data.reviewStats);
      }
      if (refRes.ok) {
        const data = await refRes.json();
        setReferralStats(data.stats);
      }
    } catch {
      /* ignore */
    }
  }, []);

  useEffect(() => {
    if (!hasAccess) return;
    fetchReviews();
    fetchReferrals();
    fetchStats();
  }, [hasAccess, fetchReviews, fetchReferrals, fetchStats]);

  if (!hasAccess) {
    return (
      <div
        className="flex flex-col items-center justify-center py-16 px-4"
        dir={isAr ? "rtl" : "ltr"}
      >
        <Lock className="w-12 h-12 text-gray-500 mb-4" />
        <h3 className="text-xl font-semibold text-slate-900 mb-2">
          {labels.upgrade}
        </h3>
        <p className="text-slate-500 text-center max-w-md mb-6">
          {labels.upgradeDesc}
        </p>
        <a
          href={`/${lang}/pricing`}
          className="px-6 py-3 bg-brand-green text-white rounded-lg hover:bg-brand-green/90"
        >
          {labels.upgradeBtn}
        </a>
      </div>
    );
  }

  const subTabs: { key: SubTab; label: string; icon: React.ReactNode }[] = [
    {
      key: "reviews",
      label: labels.reviews,
      icon: <Star className="w-4 h-4" />,
    },
    {
      key: "requests",
      label: labels.requests,
      icon: <Send className="w-4 h-4" />,
    },
    {
      key: "testimonials",
      label: labels.testimonials,
      icon: <Award className="w-4 h-4" />,
    },
    {
      key: "referrals",
      label: labels.referrals,
      icon: <Users className="w-4 h-4" />,
    },
  ];

  return (
    <div dir={isAr ? "rtl" : "ltr"} className="space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between">
        <h2 className="text-xl font-bold text-slate-900">{labels.title}</h2>
        <div className="flex items-center gap-2">
          <button
            onClick={() => {
              fetchReviews();
              fetchReferrals();
              fetchStats();
            }}
            className="p-2 text-slate-400 hover:text-slate-700"
            title={labels.refresh}
          >
            <RefreshCw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} />
          </button>
          {subTab === "reviews" && (
            <>
              <button
                onClick={() => setShowBulkRequest(true)}
                className="flex items-center gap-1 px-3 py-1.5 bg-slate-200 text-slate-700 rounded-lg hover:bg-slate-300 text-sm"
              >
                <ListChecks className="w-3.5 h-3.5" />
                {labels.bulkRequest}
              </button>
              <button
                onClick={() => setShowRequestForm(true)}
                className="flex items-center gap-1 px-3 py-1.5 bg-brand-green text-white rounded-lg hover:bg-brand-green/90 text-sm"
              >
                <Send className="w-3.5 h-3.5" />
                {labels.requestReview}
              </button>
            </>
          )}
          {subTab === "referrals" && (
            <button
              onClick={() => setShowReferralForm(true)}
              className="flex items-center gap-1 px-3 py-1.5 bg-brand-green text-white rounded-lg hover:bg-brand-green/90 text-sm"
            >
              <Plus className="w-3.5 h-3.5" />
              {labels.createCode}
            </button>
          )}
        </div>
      </div>

      {/* Sub-tabs */}
      <div className="flex gap-1 bg-slate-100 rounded-lg p-1 border border-slate-200">
        {subTabs.map((tab) => (
          <button
            key={tab.key}
            onClick={() => setSubTab(tab.key)}
            className={`flex items-center gap-2 px-4 py-2.5 rounded-md text-sm font-medium transition-colors flex-1 justify-center ${
              subTab === tab.key
                ? "bg-brand-green text-white shadow-sm"
                : "text-slate-500 hover:text-slate-900 hover:bg-slate-200"
            }`}
          >
            {tab.icon}
            {tab.label}
          </button>
        ))}
      </div>

      {/* Content */}
      {loading && reviews.length === 0 && referrals.length === 0 && (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-6 h-6 animate-spin text-brand-green" />
          <span className="ml-2 text-slate-500">{labels.loading}</span>
        </div>
      )}

      {subTab === "reviews" && (
        <div className="space-y-6">
          <ReviewStats lang={lang} stats={reviewStats} />
          <ReviewsList
            lang={lang}
            reviews={reviews}
            loading={loading}
            hasMore={reviews.length < reviewTotal}
            onLoadMore={() => fetchReviews(reviewPage + 1, true)}
            onRefresh={() => {
              fetchReviews();
              fetchStats();
            }}
          />
        </div>
      )}

      {subTab === "requests" && (
        <div className="space-y-4">
          <div className="flex justify-end">
            <button
              onClick={() => setShowRequestForm(true)}
              className="flex items-center gap-1 px-3 py-1.5 bg-brand-green text-white rounded-lg hover:bg-brand-green/90 text-sm"
            >
              <Send className="w-3.5 h-3.5" />
              {labels.requestReview}
            </button>
          </div>
          <ReviewRequestsList lang={lang} refreshTrigger={requestRefresh} />
        </div>
      )}

      {subTab === "testimonials" && (
        <div className="space-y-8">
          <div className="bg-white rounded-xl border border-slate-200 p-6">
            <ReviewQuestionEditor lang={lang} />
          </div>
          <TestimonialsList lang={lang} />
          <TestimonialsSettings lang={lang} userId={userId} />
        </div>
      )}

      {subTab === "referrals" && (
        <div className="space-y-6">
          <ReferralStats lang={lang} stats={referralStats} />
          <ReferralsList
            lang={lang}
            referrals={referrals}
            loading={loading}
            hasMore={referrals.length < referralTotal}
            onLoadMore={() => fetchReferrals(referralPage + 1, true)}
          />
        </div>
      )}

      {/* Modals */}
      {showRequestForm && (
        <ReviewRequestForm
          lang={lang}
          onClose={() => setShowRequestForm(false)}
          onSuccess={() => {
            fetchReviews();
            fetchStats();
            setRequestRefresh((n) => n + 1);
          }}
        />
      )}

      {showReferralForm && (
        <ReferralForm
          lang={lang}
          onClose={() => setShowReferralForm(false)}
          onSuccess={() => {
            fetchReferrals();
            fetchStats();
          }}
        />
      )}

      {showBulkRequest && (
        <BulkReviewRequestModal
          lang={lang}
          onClose={() => setShowBulkRequest(false)}
          onSuccess={() => {
            fetchReviews();
            fetchStats();
            setRequestRefresh((n) => n + 1);
          }}
        />
      )}
    </div>
  );
}
