"use client";

import { useState, useEffect, useCallback } from "react";
import { Star, Loader2, Quote } from "lucide-react";

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

interface WidgetData {
  businessName: string;
  logoUrl: string | null;
  primaryColor: string;
  bgColor: string;
  showPoweredBy: boolean;
  testimonials: Testimonial[];
}

interface PageProps {
  params: { lang: string; userId: string };
}

export default function EmbedTestimonialsPage({ params }: PageProps) {
  const { lang, userId } = params;
  const isAr = lang === "ar";

  const [data, setData] = useState<WidgetData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  const fetchData = useCallback(async () => {
    try {
      const res = await fetch(`/api/public/testimonials/${userId}`);
      if (res.ok) {
        const json = await res.json();
        setData(json);
      } else {
        setError(true);
      }
    } catch {
      setError(true);
    } finally {
      setLoading(false);
    }
  }, [userId]);

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

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[200px] bg-white">
        <Loader2 className="w-8 h-8 text-emerald-500 animate-spin" />
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="flex items-center justify-center min-h-[200px] bg-white">
        <p className="text-slate-400 text-sm">
          {isAr ? "تعذر تحميل الشهادات" : "Unable to load testimonials"}
        </p>
      </div>
    );
  }

  const primaryColor = data.primaryColor || "#10b981";
  const bgColor = data.bgColor || "#ffffff";

  if (data.testimonials.length === 0) {
    return (
      <div
        className="flex items-center justify-center min-h-[200px]"
        style={{ backgroundColor: bgColor }}
      >
        <p className="text-slate-400 text-sm">
          {isAr ? "لا توجد شهادات بعد" : "No testimonials yet"}
        </p>
      </div>
    );
  }

  return (
    <div
      className="p-6"
      dir={isAr ? "rtl" : "ltr"}
      style={{ backgroundColor: bgColor }}
    >
      {/* Header */}
      <div className="text-center mb-6">
        {data.logoUrl && (
          <img
            src={data.logoUrl}
            alt={data.businessName}
            className="h-8 mx-auto mb-3 object-contain"
          />
        )}
        {data.businessName && (
          <h2 className="text-lg font-semibold" style={{ color: primaryColor }}>
            {data.businessName}
          </h2>
        )}
      </div>

      {/* Testimonials Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {data.testimonials.map((testimonial) => (
          <div
            key={testimonial.id}
            className="bg-white rounded-xl shadow-sm border border-slate-100 p-5 relative"
          >
            <Quote
              className="w-6 h-6 absolute top-4 end-4 opacity-10"
              style={{ color: primaryColor }}
            />

            {/* Stars */}
            <div className="flex gap-0.5 mb-3">
              {[1, 2, 3, 4, 5].map((s) => (
                <Star
                  key={s}
                  className="w-4 h-4"
                  style={{
                    color: s <= testimonial.rating ? primaryColor : "#e5e7eb",
                    fill: s <= testimonial.rating ? primaryColor : "none",
                  }}
                />
              ))}
            </div>

            {/* Content */}
            {testimonial.content && (
              <p className="text-sm text-slate-600 leading-relaxed mb-3">
                {testimonial.content}
              </p>
            )}

            {/* Customer Name */}
            <p className="text-sm font-medium text-slate-900">
              {testimonial.customerName}
            </p>
            <p className="text-xs text-slate-400">
              {new Date(testimonial.createdAt).toLocaleDateString(
                isAr ? "ar" : "en",
              )}
            </p>
          </div>
        ))}
      </div>

      {/* Powered by */}
      {data.showPoweredBy && (
        <p className="text-center text-xs text-slate-400 mt-6">
          {isAr ? "مدعوم من Mawidi" : "Powered by Mawidi"}
        </p>
      )}
    </div>
  );
}
