"use client";

import React, { useState } from "react";
import { toast } from "sonner";
import { MessageSquare, Check, X, Trash2, StarIcon, EyeIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/page-header";
import { updateReviewStatus, deleteReview } from "@/app/actions/reviews";
import { format } from "date-fns-jalali";

export default function ReviewsClient({ initialReviews }: { initialReviews: any[] }) {
  const [reviews, setReviews] = useState(initialReviews);
  const [loading, setLoading] = useState<string | null>(null);

  const handleUpdateStatus = async (id: string, status: string) => {
    setLoading(id);
    const res = await updateReviewStatus(id, status);
    setLoading(null);
    if (res.success) {
      toast.success(status === "APPROVED" ? "نظر تایید شد" : "نظر رد شد");
      setReviews(reviews.map(r => r.id === id ? { ...r, status } : r));
    } else {
      toast.error("خطا: " + res.error);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("آیا از حذف این نظر مطمئن هستید؟")) return;
    setLoading(id);
    const res = await deleteReview(id);
    setLoading(null);
    if (res.success) {
      toast.success("نظر حذف شد");
      setReviews(reviews.filter(r => r.id !== id));
    } else {
      toast.error("خطا در حذف نظر: " + res.error);
    }
  };

  return (
    <div className="flex flex-col h-full bg-background" dir="rtl">
      <PageHeader
        title="نظرات کاربران"
        subtitle="مدیریت و بررسی نظرات ثبت شده برای محصولات فروشگاه"
        icon={<MessageSquare className="w-5 h-5" />}
      />

      <main className="flex-1 p-4 md:p-6 bg-muted/20 overflow-y-auto">
        <div className="max-w-6xl mx-auto space-y-6">
          <div className="bg-card border rounded-3xl shadow-sm overflow-hidden">
            <div className="overflow-x-auto">
              <table className="w-full text-sm text-right">
                <thead className="bg-muted/50 border-b text-xs text-muted-foreground">
                  <tr>
                    <th className="p-4 font-bold">محصول</th>
                    <th className="p-4 font-bold">کاربر</th>
                    <th className="p-4 font-bold">امتیاز</th>
                    <th className="p-4 font-bold w-1/3">متن نظر</th>
                    <th className="p-4 font-bold">تاریخ</th>
                    <th className="p-4 font-bold">وضعیت</th>
                    <th className="p-4 font-bold">عملیات</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {reviews.length === 0 ? (
                    <tr><td colSpan={7} className="p-8 text-center text-muted-foreground">هیچ نظری تاکنون ثبت نشده است.</td></tr>
                  ) : (
                    reviews.map(review => (
                      <tr key={review.id} className="hover:bg-muted/30 transition-colors">
                        <td className="p-4 align-top">
                          <p className="font-bold line-clamp-1">{review.product?.name || "محصول حذف شده"}</p>
                          <p className="text-xs text-muted-foreground mt-1" dir="ltr">{review.product?.sku}</p>
                        </td>
                        <td className="p-4 align-top">
                          <p className="font-bold">{review.user ? `${review.user.firstName || ''} ${review.user.lastName || ''}`.trim() || 'کاربر توکان' : 'کاربر مهمان'}</p>
                          {review.user?.phone && <p className="text-xs text-muted-foreground mt-1" dir="ltr">{review.user.phone}</p>}
                        </td>
                        <td className="p-4 align-top">
                          <div className="flex items-center gap-0.5 text-amber-500">
                            {Array.from({ length: 5 }).map((_, i) => (
                              <StarIcon key={i} className={`w-3.5 h-3.5 ${i < review.rating ? 'fill-current' : 'text-slate-200 dark:text-slate-700'}`} />
                            ))}
                          </div>
                        </td>
                        <td className="p-4 align-top">
                          {review.title && <p className="font-bold mb-1 text-sm">{review.title}</p>}
                          <p className="text-xs text-muted-foreground leading-relaxed line-clamp-3">{review.content}</p>
                        </td>
                        <td className="p-4 align-top text-xs font-mono text-muted-foreground" dir="ltr">
                          {format(new Date(review.createdAt), "yyyy/MM/dd HH:mm")}
                        </td>
                        <td className="p-4 align-top">
                          {review.status === "PENDING" && <span className="px-2 py-1 bg-amber-100 text-amber-700 text-[10px] rounded-full font-bold">در انتظار تایید</span>}
                          {review.status === "APPROVED" && <span className="px-2 py-1 bg-emerald-100 text-emerald-700 text-[10px] rounded-full font-bold">تایید شده</span>}
                          {review.status === "REJECTED" && <span className="px-2 py-1 bg-rose-100 text-rose-700 text-[10px] rounded-full font-bold">رد شده</span>}
                        </td>
                        <td className="p-4 align-top">
                          <div className="flex gap-2">
                            {review.status !== "APPROVED" && (
                              <Button 
                                size="sm" 
                                variant="outline" 
                                className="h-8 bg-emerald-50 text-emerald-600 hover:bg-emerald-100 hover:text-emerald-700 border-emerald-200"
                                onClick={() => handleUpdateStatus(review.id, "APPROVED")}
                                disabled={loading === review.id}
                              >
                                <Check className="w-4 h-4 ml-1" /> تایید
                              </Button>
                            )}
                            {review.status !== "REJECTED" && (
                              <Button 
                                size="sm" 
                                variant="outline" 
                                className="h-8 bg-rose-50 text-rose-600 hover:bg-rose-100 hover:text-rose-700 border-rose-200"
                                onClick={() => handleUpdateStatus(review.id, "REJECTED")}
                                disabled={loading === review.id}
                              >
                                <X className="w-4 h-4 ml-1" /> رد
                              </Button>
                            )}
                            <Button size="icon" variant="ghost" className="h-8 w-8 text-slate-400 hover:text-rose-500" onClick={() => handleDelete(review.id)} disabled={loading === review.id}>
                              <Trash2 className="w-4 h-4" />
                            </Button>
                          </div>
                        </td>
                      </tr>
                    ))
                  )}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
}
