"use client";
import React, { useEffect, useState } from "react";
import Link from "next/link";
import Loader from "@/components/common/Loader";
import { FaStar, FaEllipsisH } from "react-icons/fa";
import {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
} from "@/components/ui/dropdown-menu";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
  DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { toast } from "react-toastify";

type ReviewType = {
  id: number;
  review: string;
  rating: number;
  variant?: { uuid: string; name: string } | null;
};

export default function ReviewsPageWithPrompts() {
  const [isLoading, setIsLoading] = useState(true);
  const [productReviews, setProductReviews] = useState<ReviewType[]>([]);
  const [page, setPage] = useState(1);
  const [limit] = useState(10);
  const [total, setTotal] = useState(0);

  // edit state
  const [editText, setEditText] = useState("");
  const [editRating, setEditRating] = useState<number>(5);
  const [isSaving, setIsSaving] = useState(false);
  const [selectedReview, setSelectedReview] = useState<ReviewType | null>(null);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);

  // delete state
  const [isDeleting, setIsDeleting] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);

  useEffect(() => {
    const fetchReviews = async () => {
      try {
        setIsLoading(true);
        const res = await fetch(`/api/user/review?page=${page}&limit=${limit}`);
        const data = await res.json();
        setProductReviews(data.data || []);
        setTotal(data.total || 0);
      } catch (err) {
        console.error("Failed to fetch reviews", err);
      } finally {
        setIsLoading(false);
      }
    };
    fetchReviews();
  }, [page, limit]);

  const handleSaveEdit = async () => {
    if (!selectedReview) return;
    setIsSaving(true);
    try {
      const res = await fetch(`/api/user/review/${selectedReview.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ review: editText, rating: editRating }),
      });
      if (!res.ok) throw new Error("Failed to save");

      setProductReviews((prev) =>
        prev.map((p) =>
          p.id === selectedReview.id
            ? { ...p, review: editText, rating: editRating }
            : p
        )
      );

      toast.success("Review updated successfully");

      setIsEditDialogOpen(false);
      setSelectedReview(null);
    } catch (err) {
      console.error(err);
    } finally {
      setIsSaving(false);
    }
  };

  const handleConfirmDelete = async () => {
    if (!selectedReview) return;
    setIsDeleting(true);
    try {
      const res = await fetch(`/api/user/review/${selectedReview.id}`, {
        method: "DELETE",
      });
      if (!res.ok) throw new Error("Delete failed");

      setProductReviews((prev) =>
        prev.filter((p) => p.id !== selectedReview.id)
      );
      setSelectedReview(null);
      setIsDeleteDialogOpen(false);

      toast.success("Review deleted successfully");
    } catch (err) {
      console.error(err);
    } finally {
      setIsDeleting(false);
    }
  };

  const totalPages = Math.ceil(total / limit) || 1;

  if (isLoading)
    return (
      <div className="flex justify-center items-center h-40">
        <Loader />
      </div>
    );

  return (
    <section className="space-y-2 py-5 px-2">
      <div className="gap-4 sm:flex sm:items-center sm:justify-between pb-6">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">My reviews</h1>
          <p className="text-muted-foreground">Manage your reviews.</p>
        </div>
      </div>

      <div className="mt-6 flow-root sm:mt-8">
        {productReviews.length === 0 ? (
          <div className="rounded-lg border border-dashed border-gray-200 bg-gray-50 p-8 text-center">
            <p className="text-lg font-medium text-gray-700">No reviews yet</p>
            <p className="text-sm text-gray-500 mt-2">
              You haven’t written any reviews yet.
            </p>
            <Link href="/" className="inline-block mt-4">
              <Button>Browse products</Button>
            </Link>
          </div>
        ) : (
          <div className="space-y-6">
            {productReviews.map((review) => (
              <div
                key={review.id}
                className="grid md:grid-cols-12 gap-4 md:gap-6 pb-4 md:pb-6 border-b border-gray-200"
              >
                <dl className="md:col-span-3">
                  <dd className="text-base font-semibold text-gray-900">
                    <Link href={`/products/${review.variant?.uuid}`}>
                      {review.variant?.name}
                    </Link>
                  </dd>
                </dl>

                <dl className="md:col-span-6">
                  <dd className="text-gray-600">{review.review}</dd>
                </dl>

                <div className="md:col-span-3 flex items-center justify-between">
                  <div className="flex items-center">
                    {[...Array(5)].map((_, i) => (
                      <FaStar
                        key={i}
                        className={`w-4 h-4 ${
                          i < review.rating ? "text-yellow-400" : "text-gray-300"
                        }`}
                      />
                    ))}
                  </div>

                  <DropdownMenu>
                    <DropdownMenuTrigger asChild>
                      <Button
                        variant="outline"
                        size="icon"
                        className="h-8 w-8 p-0"
                      >
                        <FaEllipsisH />
                      </Button>
                    </DropdownMenuTrigger>

                    <DropdownMenuContent align="end" className="w-44">
                      <DropdownMenuLabel>Actions</DropdownMenuLabel>

                      <DropdownMenuItem
                        onClick={() => {
                          setSelectedReview(review);
                          setEditText(review.review);
                          setEditRating(review.rating);
                          setIsEditDialogOpen(true);
                        }}
                      >
                        Edit review
                      </DropdownMenuItem>

                      <DropdownMenuItem
                        onClick={() => {
                          setSelectedReview(review);
                          setIsDeleteDialogOpen(true);
                        }}
                        className="text-red-600"
                      >
                        Delete review
                      </DropdownMenuItem>
                    </DropdownMenuContent>
                  </DropdownMenu>
                </div>
              </div>
            ))}

            {/* Pagination */}
            <div className="flex justify-center items-center mt-6 space-x-4">
              <Button
                variant="ghost"
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1}
              >
                Previous
              </Button>
              <span className="text-sm">
                Page {page} of {totalPages}
              </span>
              <Button
                variant="ghost"
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page === totalPages}
              >
                Next
              </Button>
            </div>
          </div>
        )}
      </div>

      {/* Edit Dialog */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="bg-white">
          <DialogHeader>
            <DialogTitle>Edit review</DialogTitle>
            <DialogDescription>
              Update your review and rating.
            </DialogDescription>
          </DialogHeader>

          <div className="grid gap-2 py-4">
            <div>
              <Label>Rating</Label>
              <div className="flex items-center gap-2 mt-2">
                {[1, 2, 3, 4, 5].map((n) => (
                  <button
                    key={n}
                    type="button"
                    onClick={() => setEditRating(n)}
                    className={`p-1 rounded ${
                      n <= editRating ? "bg-yellow-100" : "bg-transparent"
                    }`}
                  >
                    <FaStar
                      className={`w-5 h-5 ${
                        n <= editRating ? "text-yellow-400" : "text-gray-300"
                      }`}
                    />
                  </button>
                ))}
              </div>
            </div>

            <div>
              <Label>Review</Label>
              <Textarea
                value={editText}
                onChange={(e) => setEditText(e.target.value)}
                rows={4}
              />
            </div>
          </div>

          <DialogFooter>
            <Button
              variant="ghost"
              onClick={() => {
                setIsEditDialogOpen(false);
                setSelectedReview(null);
              }}
            >
              Cancel
            </Button>
            <Button onClick={handleSaveEdit} disabled={isSaving}>
              {isSaving ? "Saving..." : "Save"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Delete Dialog */}
      <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <DialogContent className="bg-white">
          <DialogHeader>
            <DialogTitle>Delete review</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete this review? This action cannot be
              undone.
            </DialogDescription>
          </DialogHeader>

          <div className="py-4">
            <p className="text-sm text-gray-600">
              Review: {selectedReview?.review}
            </p>
          </div>

          <DialogFooter>
            <Button
              variant="ghost"
              onClick={() => {
                setIsDeleteDialogOpen(false);
                setSelectedReview(null);
              }}
            >
              Cancel
            </Button>
            <Button
              className="bg-red-600 text-white"
              onClick={handleConfirmDelete}
              disabled={isDeleting}
            >
              {isDeleting ? "Deleting..." : "Delete"}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </section>
  );
}
