"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Star,
  Pin,
  PinOff,
  ChevronUp,
  ChevronDown,
  Loader2,
  Quote,
} from "lucide-react";
import { fetchWithCSRF } from "@/lib/csrf-client";

const t = {
  en: {
    title: "Featured Testimonials",
    pin: "Pin",
    unpin: "Unpin",
    noTestimonials:
      "No featured testimonials yet. Pin reviews to showcase them.",
    loadError: "Failed to load testimonials",
    pinError: "Failed to update pin status",
    moveUp: "Move up",
    moveDown: "Move down",
  },
  ar: {
    title: "الشهادات المميزة",
    pin: "تثبيت",
    unpin: "إلغاء التثبيت",
    noTestimonials: "لا توجد شهادات مميزة بعد. قم بتثبيت التقييمات لعرضها.",
    loadError: "فشل في تحميل الشهادات",
    pinError: "فشل في تحديث حالة التثبيت",
    moveUp: "نقل لأعلى",
    moveDown: "نقل لأسفل",
  },
};

interface Testimonial {
  id: string;
  customerName: string;
  rating: number;
  content: string | null;
  isFeatured: boolean;
  sortOrder: number;
  createdAt: string;
}

interface TestimonialsListProps {
  lang: string;
}

export default function TestimonialsList({ lang }: TestimonialsListProps) {
  const isAr = lang === "ar";
  const labels = t[isAr ? "ar" : "en"];

  const [testimonials, setTestimonials] = useState<Testimonial[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const fetchTestimonials = useCallback(async () => {
    try {
      const res = await fetchWithCSRF("/api/dashboard/reviews/testimonials");
      if (res.ok) {
        const data = await res.json();
        setTestimonials(data.testimonials ?? []);
      } else {
        setError(labels.loadError);
      }
    } catch {
      setError(labels.loadError);
    } finally {
      setLoading(false);
    }
  }, [labels.loadError]);

  useEffect(() => {
    fetchTestimonials();
  }, [fetchTestimonials]);

  const togglePin = async (id: string, currentlyFeatured: boolean) => {
    setError("");
    try {
      const res = await fetchWithCSRF("/api/dashboard/reviews/testimonials", {
        method: "POST",
        body: JSON.stringify({ reviewId: id, featured: !currentlyFeatured }),
      });
      if (!res.ok) throw new Error("Failed");
      await fetchTestimonials();
    } catch {
      setError(labels.pinError);
    }
  };

  const handleReorder = async (index: number, direction: "up" | "down") => {
    const featured = testimonials.filter((t) => t.isFeatured);
    const targetIndex = direction === "up" ? index - 1 : index + 1;
    if (targetIndex < 0 || targetIndex >= featured.length) return;

    const newFeatured = [...featured];
    [newFeatured[index], newFeatured[targetIndex]] = [
      newFeatured[targetIndex],
      newFeatured[index],
    ];

    const reordered = newFeatured.map((t, i) => ({ ...t, sortOrder: i }));
    const unfeatured = testimonials.filter((t) => !t.isFeatured);
    setTestimonials([...reordered, ...unfeatured]);

    try {
      await fetchWithCSRF("/api/dashboard/reviews/testimonials", {
        method: "PUT",
        body: JSON.stringify({
          orderedIds: reordered.map((t) => t.id),
        }),
      });
    } catch {
      await fetchTestimonials();
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <Loader2 className="w-6 h-6 animate-spin text-brand-green" />
      </div>
    );
  }

  const featured = testimonials.filter((t) => t.isFeatured);
  const unfeatured = testimonials.filter((t) => !t.isFeatured);

  return (
    <div dir={isAr ? "rtl" : "ltr"} className="space-y-4">
      <h3 className="text-lg font-semibold text-slate-900">{labels.title}</h3>

      {error && (
        <p className="text-sm text-red-600 bg-red-50 px-3 py-2 rounded-lg">
          {error}
        </p>
      )}

      {testimonials.length === 0 && (
        <div className="text-center py-8 text-slate-500">
          {labels.noTestimonials}
        </div>
      )}

      {/* Featured (pinned) testimonials */}
      {featured.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {featured.map((testimonial, index) => (
            <div
              key={testimonial.id}
              className="bg-slate-50 rounded-lg p-4 border border-brand-green/30 relative"
            >
              <div className="flex items-start justify-between gap-2 mb-3">
                <div className="flex items-center gap-0.5">
                  {[1, 2, 3, 4, 5].map((s) => (
                    <Star
                      key={s}
                      className={`w-3.5 h-3.5 ${
                        s <= testimonial.rating
                          ? "text-yellow-400 fill-current"
                          : "text-gray-600"
                      }`}
                    />
                  ))}
                </div>
                <div className="flex items-center gap-1">
                  <button
                    onClick={() => handleReorder(index, "up")}
                    disabled={index === 0}
                    className="p-1 text-slate-400 hover:text-slate-700 disabled:opacity-30"
                    title={labels.moveUp}
                  >
                    <ChevronUp className="w-3.5 h-3.5" />
                  </button>
                  <button
                    onClick={() => handleReorder(index, "down")}
                    disabled={index === featured.length - 1}
                    className="p-1 text-slate-400 hover:text-slate-700 disabled:opacity-30"
                    title={labels.moveDown}
                  >
                    <ChevronDown className="w-3.5 h-3.5" />
                  </button>
                  <button
                    onClick={() => togglePin(testimonial.id, true)}
                    className="p-1 text-brand-green hover:text-brand-green/80"
                    title={labels.unpin}
                  >
                    <PinOff className="w-3.5 h-3.5" />
                  </button>
                </div>
              </div>
              <Quote className="w-5 h-5 text-brand-green/30 mb-2" />
              <p className="text-sm text-slate-600 line-clamp-3">
                {testimonial.content}
              </p>
              <p className="text-xs text-gray-500 mt-3 font-medium">
                {testimonial.customerName}
              </p>
            </div>
          ))}
        </div>
      )}

      {/* Unfeatured reviews */}
      {unfeatured.length > 0 && (
        <div className="space-y-2">
          {unfeatured.map((testimonial) => (
            <div
              key={testimonial.id}
              className="bg-slate-50 rounded-lg p-3 border border-slate-200 flex items-center gap-3"
            >
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 mb-0.5">
                  <span className="text-sm font-medium text-slate-900">
                    {testimonial.customerName}
                  </span>
                  <div className="flex items-center gap-0.5">
                    {[1, 2, 3, 4, 5].map((s) => (
                      <Star
                        key={s}
                        className={`w-3 h-3 ${
                          s <= testimonial.rating
                            ? "text-yellow-400 fill-current"
                            : "text-gray-600"
                        }`}
                      />
                    ))}
                  </div>
                </div>
                {testimonial.content && (
                  <p className="text-xs text-slate-500 truncate">
                    {testimonial.content}
                  </p>
                )}
              </div>
              <button
                onClick={() => togglePin(testimonial.id, false)}
                className="flex items-center gap-1 text-xs text-slate-400 hover:text-brand-green shrink-0"
              >
                <Pin className="w-3.5 h-3.5" />
                {labels.pin}
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
