"use client";

import { useState, useEffect } from "react";
import { Button } from "../../../../../src/components/ui/button";
import { Input } from "../../../../../src/components/ui/input";
import { Label } from "../../../../../src/components/ui/label";
import { Textarea } from "../../../../../src/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../../../src/components/ui/select";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "../../../../../src/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../../src/components/ui/table";
import { Badge } from "../../../../../src/components/ui/badge";
import { Edit, Trash2, Search, ChevronLeft, ChevronRight, Eye, Star, Plus, Upload, X, ArrowUp, ArrowDown, ArrowUpDown } from "lucide-react";
import { toast } from "sonner";
import Editor from "../../../../../src/app/admin/_components/editor/Editor";
import { Tooltip } from "../../../../../src/components/ui/tooltip";
import { useDebounce } from "../../../../../src/hooks/useDebounce";
import { Interweave } from 'interweave'


type Customer = { _id: string; name: string; email: string }

interface Review {
  _id: string;
  product: { _id: string; name: string; slug: string };
  customer: Customer;
  authorName: string;
  authorEmail: string;
  reviewTitle: string;
  reviewDescription: string;
  rating: number;
  images: string[] | null;
  status: 'approved' | 'not-approved';
  createdAt: string;
  updatedAt: string;
}

const statusVariant: Record<string, 'default' | 'secondary' | 'destructive'> = {
  'not-approved': 'default',
  'approved':  'secondary',
};

const statusLabel: Record<string, string> = {
  approved: 'Approved',
  'not-approved':  'Not approved',
};

function StarRating({ rating }: { rating: number }) {
  return (
    <div className="flex items-start justify-start gap-0.5">
      {[1, 2, 3, 4, 5].map((star) => (
        <Star
          key={star}
          className={`w-3.5 h-3.5 ${star <= rating ? 'fill-yellow-400 text-yellow-400' : 'text-gray-300'}`}
        />
      ))}
    </div>
  );
}

export default function ManageReview() {
  const [reviews, setReviews] = useState<Review[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [statusFilter, setStatusFilter] = useState("");
  const [sortField, setSortField] = useState<"createdAt" | "product" | "authorName" | "rating" | "status">("createdAt");
  const [sortOrder, setSortOrder] = useState<"asc" | "desc">("asc");
  const [pagination, setPagination] = useState({ total: 0, pages: 0, page: 1, limit: 10 });
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isViewOpen, setIsViewOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isAddOpen, setIsAddOpen] = useState(false);
  const [selectedReview, setSelectedReview] = useState<Review | null>(null);
  const [updatingStatus, setUpdatingStatus] = useState(false);
  const [allProductOptions, setAllProductOptions] = useState([])
  const [productsLoading, setProductsLoading] = useState(false)
  const [customer, setCustomer] = useState({
    _id: '',
    name: '',
    email: '',
  })

  const [editForm, setEditForm] = useState({
    product: "",
    customer: "",
    authorName: "",
    authorEmail: "",
    reviewTitle: "",
    reviewDescription: "",
    rating: 5,
    status: "not-approved",
    newImages: [] as File[],
    removedImages: [] as string[],
    existingImages: [] as string[],
  });

  const debouncedSearch = useDebounce(search, 500)

  useEffect(() => { fetchReviews(); }, [debouncedSearch, page, limit, statusFilter, sortField, sortOrder]);

  const fetchReviews = async () => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        page: page.toString(),
        limit: limit.toString(),
        sort: sortField,
        order: sortOrder,
        ...(debouncedSearch && { search: debouncedSearch }),
        ...(statusFilter && { status: statusFilter }),
      });
      const res = await fetch(`/api/reviews?${params}`);
      const result = await res.json();
      if (result.success) {
        setReviews(result.data);
        setPagination(result.pagination);
      } else {
        toast.error('Failed to fetch reviews');
      }
    } catch {
      toast.error('Error fetching reviews');
    } finally {
      setLoading(false);
    }
  };

  const handleLimitChange = (value: string) => {
    const newLimit = parseInt(value);
    setLimit(newLimit);
    setPage(1);
  };

  const handleSort = (field: "createdAt" | "product" | "authorName" | "rating" | "status") => {
    if (sortField === field) {
      setSortOrder(sortOrder === "asc" ? "desc" : "asc");
    } else {
      setSortField(field);
      if (field === "rating" || field === "authorName" || field === "product") {
        setSortOrder("asc");
      } else {
        setSortOrder("desc");
      }
    }
    setPage(1);
  };

  const fetchProducts = async () => {
    setProductsLoading(true)
    try{
        const res: any = await fetch('/api/products')
        const apiData = await res.json()

        if(apiData.success){
            const options = apiData.data?.map((dt: any) => ({
                value: dt._id,
                label: `${dt.name}(${dt.category?.name})`
            }))

            setAllProductOptions(options)
        }
    } catch(error){
        console.error('Error fetching products', error)
    } finally {
        setProductsLoading(false)
    }
  }

  useEffect(() => {
    // fetch user details
    (() => {
        const rawUser = localStorage.getItem('user')
        if(rawUser){
            const parsedUser = JSON.parse(rawUser)
            setCustomer({
                _id: parsedUser?._id,
                name: parsedUser?.name,
                email: parsedUser?.email,
            })
        }
    })()
  }, [])

  useEffect(() => {
    if(isAddOpen || isEditOpen) fetchProducts()
  }, [isAddOpen, isEditOpen])

  const handleView = (review: Review) => {
    setSelectedReview(review);
    setIsViewOpen(true);
  };

  const handleAdd = () => {
    setSelectedReview(null);
    resetForm();
    setIsAddOpen(true);
  };

  const handleEdit = (review: Review) => {
    setSelectedReview(review);
    setEditForm({
      reviewTitle: review.reviewTitle,
      reviewDescription: review.reviewDescription,
      rating: review.rating,
      status: review.status,
      newImages: [],
      removedImages: [],
      existingImages: review.images || [],
      product: review.product._id,
      customer: review.customer._id,
      authorName: review.authorName,
      authorEmail: review.authorEmail,
    });
    setIsEditOpen(true);
  };

  const resetForm = () => {
    setEditForm({
      reviewTitle: '',
      reviewDescription: '',
      rating: 5,
      status: '',
      newImages: [],
      removedImages: [],
      existingImages: [],
      product: "",
      customer: "",
      authorName: "",
      authorEmail: "",
    });
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    console.log('DForm', editForm)
    // return
    const isEditing = !!selectedReview;
    setIsSubmitting(true)
    try {
        const form = new FormData();
        form.append('reviewTitle', editForm.reviewTitle);
        form.append('reviewDescription', editForm.reviewDescription);
        form.append('rating', editForm.rating.toString());
        form.append('status', editForm.status);

        // Append new image files
        editForm.newImages.forEach((file) => {
        form.append('images', file);
        });

        if (isEditing) {
        // PUT — images to remove only needed on edit
        if (editForm.removedImages.length > 0) {
            form.append('removeImages', JSON.stringify(editForm.removedImages));
        }
        } else {
            // POST — extra required fields for create
            form.append('product',     editForm.product);
            form.append('customer', customer._id);
            form.append('authorName', customer.name);
            form.append('authorEmail', customer.email);
        }

        const url = isEditing ? `/api/reviews/${selectedReview._id}` : '/api/reviews';
        const method = isEditing ? 'PUT' : 'POST';

        const res    = await fetch(url, { method, body: form });
        const result = await res.json();

        if (result.success) {
        toast.success(isEditing ? 'Review updated successfully' : 'Review created successfully');
        setIsEditOpen(false);
        setIsAddOpen(false);
        setSelectedReview(null);
        resetForm();
        fetchReviews();
        } else {
        toast.error(result.error || 'Failed to save review');
        }
    } catch {
        toast.error('Error saving review');
    } finally{
        setIsSubmitting(false)
    }
  };

  const handleStatusChange = async (review: Review, newStatus: string) => {
    setUpdatingStatus(true);
    try {
      const form = new FormData();
      form.append('status', newStatus);
      const res    = await fetch(`/api/reviews/${review._id}`, { method: 'PUT', body: form });
      const result = await res.json();
      if (result.success) {
        toast.success(`Review ${newStatus}`);
        fetchReviews();
      } else {
        toast.error(result.error || 'Failed to update status');
      }
    } catch {
      toast.error('Error updating status');
    } finally {
      setUpdatingStatus(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Are you sure you want to delete this review?')) return;
    try {
      const res    = await fetch(`/api/reviews/${id}`, { method: 'DELETE' });
      const result = await res.json();
      if (result.success) {
        toast.success('Review deleted successfully');
        fetchReviews();
      } else {
        toast.error(result.error || 'Failed to delete review');
      }
    } catch {
      toast.error('Error deleting review');
    }
  };

  const formatDate = (dateString: string) =>
    new Date(dateString).toLocaleDateString('en-US', {
      year: 'numeric', month: 'long', day: 'numeric',
      hour: '2-digit', minute: '2-digit',
    });

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex justify-between items-center">
        {/* <h2 className="text-2xl font-bold">Manage Reviews</h2> */}
        
        <div className="flex items-center gap-3">
          <div className="text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded">
            Total Reviews: {pagination.total}
          </div>
          
          {/* <Button className="text-white" onClick={handleAdd}>
            <Plus className="w-4 h-4 mr-2" />
            Add Review
          </Button> */}
        </div>
      </div>

      {/* Search + Filter + Limit Dropdown */}
      <div className="flex items-center gap-4 flex-wrap">
        <div className="relative flex-1 max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 h-4 w-4" />
          <Input
            placeholder="Search reviews..."
            value={search}
            onChange={(e) => { setSearch(e.target.value); setPage(1); }}
            className="pl-10"
          />
            <X
            className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 h-4 w-4 cursor-pointer"
            onClick={() => setSearch('')}
          />
        </div>
        
        <select
          value={statusFilter}
          onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }}
          className="px-3 py-2.5 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50"
        >
          <option value="">All Status</option>          
          <option value="approved">Approved</option>
          <option value="not-approved">Not Approved</option>
        </select>
        
        {/* PAGINATION LIMIT DROPDOWN */}
        <div className="flex items-center gap-2">
          <Label className="text-sm whitespace-nowrap">Show:</Label>
          <select
            value={limit.toString()}
            onChange={(e) => handleLimitChange(e.target.value)}
            className="px-3 py-2.5 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50"
          >
            <option value="6">6</option>
            <option value="10">10</option>
            <option value="20">20</option>
            <option value="50">50</option>
          </select>
        </div>
      </div>

      {/* Table */}
      <div className="rounded-md border bg-white dark:bg-gray-900">
        <Table>
          <TableHeader className="bg-gray-100 dark:bg-gray-800">
            <TableRow className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
              {/* ID Column with Sort */}
              <TableHead 
                className="text-center cursor-pointer hover:bg-gray-50" 
                onClick={() => handleSort("createdAt")}
              >
                <div className="flex items-center justify-center gap-2">
                  ID
                  {sortField === "createdAt" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ): (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              
              {/* Product Column with Sort */}
              <TableHead 
                className="text-center cursor-pointer hover:bg-gray-50" 
                onClick={() => handleSort("product")}
              >
                <div className="flex items-center justify-center gap-2">
                  Product
                  {sortField === "product" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ): (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              
              {/* Author Column with Sort */}
              <TableHead 
                className="text-center cursor-pointer hover:bg-gray-50" 
                onClick={() => handleSort("authorName")}
              >
                <div className="flex items-center justify-center gap-2">
                  Author
                  {sortField === "authorName" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ): (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              
              <TableHead className="text-center">Review Title</TableHead>
              
              {/* Rating Column with Sort */}
              <TableHead 
                className="text-center cursor-pointer hover:bg-gray-50" 
                onClick={() => handleSort("rating")}
              >
                <div className="flex items-center justify-center gap-2">
                  Rating
                  {sortField === "rating" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ): (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              
              {/* Status Column with Sort */}
              <TableHead 
                className="text-center cursor-pointer hover:bg-gray-50" 
                onClick={() => handleSort("status")}
              >
                <div className="flex items-center justify-center gap-2">
                  Status
                  {sortField === "status" ? (
                    sortOrder === "asc" ? (
                      <ArrowUp className="h-4 w-4" />
                    ) : (
                      <ArrowDown className="h-4 w-4" />
                    )
                  ): (
                    <ArrowUpDown className="h-4 w-4 text-gray-400" />
                  )}
                </div>
              </TableHead>
              
              <TableHead className="text-center">Action</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {loading ? (
              <TableRow className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                <TableCell colSpan={7} className="px-4 py-8 text-center">
                  <div className="flex items-center justify-center">
                    <div className="h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"></div>
                    <span className="ml-2">Loading...</span>
                  </div>
                </TableCell>
              </TableRow>)
            : reviews.length === 0 ? (
              <TableRow className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                <TableCell colSpan={7} className="text-center py-10 text-muted-foreground">
                  No reviews found
                </TableCell>
              </TableRow>
            ) : (
              reviews.map((review, index) => (
                <TableRow key={review._id} className='bg-white dark:bg-gray-900 hover:bg-gray-50 dark:hover:bg-gray-800'>
                  <TableCell className="text-center">
                    {sortField === "createdAt" && sortOrder === "desc"
                      ? pagination.total - ((pagination.page - 1) * pagination.limit) - index  // desc
                      : ((pagination.page - 1) * pagination.limit) + index + 1                 // asc
                    }
                  </TableCell>
                  <TableCell className="text-center">
                    {review.product?.name || '—'}
                  </TableCell>
                  <TableCell className="text-center">
                    {review.authorName}
                  </TableCell>
                  <TableCell className="text-center max-w-[180px] truncate">
                    {review.reviewTitle}
                  </TableCell>
                  <TableCell className="text-center">
                    <StarRating rating={review.rating} />
                  </TableCell>

                  <TableCell className="text-center">
                    <button
                      onClick={() => handleStatusChange(review, review.status === 'approved' ? 'not-approved' : 'approved')}
                      className={`
                        relative inline-flex h-6 w-11 items-center rounded-full transition-colors focus:outline-none focus:ring-2 focus:ring-primary focus:ring-offset-2
                        ${review.status === 'approved' ? 'bg-green-500' : 'bg-gray-400'}
                      `}
                    >
                      <span
                        className={`
                          inline-block h-4 w-4 transform rounded-full bg-white transition-transform
                          ${review.status === 'approved' ? 'translate-x-6' : 'translate-x-1'}
                        `}
                      />
                    </button>
                    <span className="ml-2 text-xs text-muted-foreground">
                      {review.status === 'approved' ? 'Approved' : 'Not Approved'}
                    </span>
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="flex justify-center gap-1">
                      <Tooltip text="View">
                        <Button size="sm" variant="outline" onClick={() => handleView(review)}>
                          <Eye className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                      {/* <Tooltip text="Edit">
                        <Button size="sm" variant="outline" onClick={() => handleEdit(review)}>
                          <Edit className="w-4 h-4" />
                        </Button>
                      </Tooltip> */}
                      <Tooltip text="Delete">
                        <Button size="sm" variant="outline" onClick={() => handleDelete(review._id)}>
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </Tooltip>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      {pagination.pages > 1 && (
        <div className="flex items-center justify-between">
          <div className="text-sm text-gray-500">
            Showing {((page - 1) * limit) + 1} to {Math.min(page * limit, pagination.total)} of {pagination.total} results
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={() => setPage(page - 1)} disabled={page === 1}>
              <ChevronLeft className="h-4 w-4" /> Previous
            </Button>
            <span className="text-sm">Page {page} of {pagination.pages}</span>
            <Button variant="outline" size="sm" onClick={() => setPage(page + 1)} disabled={page === pagination.pages}>
              Next <ChevronRight className="h-4 w-4" />
            </Button>
          </div>
        </div>
      )}

      {/* View Dialog */}
      <Dialog open={isViewOpen} onOpenChange={setIsViewOpen}>
        <DialogContent className="max-w-2xl">
          <div className="flex items-center max-w-lg min-h-[calc(100%-0.5rem)] my-1 mx-auto">
            <div className="relative flex flex-col w-full rounded-lg gap-0 border-0 border-stroke bg-white p-0 shadow-lg text-dark-5 dark:border-dark-3 dark:bg-[#1f2a37] dark:text-white">
              {/* Fixed Header */}
              <DialogHeader className="flex-shrink-0">
                <DialogTitle>Review Details</DialogTitle>
                <X className="h-6 w-6 p-1 text-white cursor-pointer"
                  onClick={() => {
                    setIsViewOpen(false);
                  }}
                />
              </DialogHeader>

              {selectedReview && (
                <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
                  <div className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">

                    <div className="grid md:grid-cols-2 gap-4">
                      <div>
                        <Label className="text-xs text-muted-foreground">Product</Label>
                        <p className="text-sm font-medium mt-0.5">
                          {selectedReview.product?.name || '—'}
                        </p>
                      </div>

                      <div>
                        <Label className="text-xs text-muted-foreground">Author</Label>
                        <p className="text-sm font-medium mt-0.5">
                          {selectedReview.authorName}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {selectedReview.authorEmail}
                        </p>
                      </div>

                      <div>
                        <Label className="text-xs text-muted-foreground">Review Title</Label>
                        <p className="text-sm font-medium mt-0.5">
                          {selectedReview.reviewTitle}
                        </p>
                      </div>

                      <div>
                        <Label className="text-xs text-muted-foreground">Rating</Label>
                        <div className="text-start mt-1">
                          <StarRating rating={selectedReview.rating} />
                        </div>
                      </div>

                      <div>
                        <Label className="text-xs text-muted-foreground">Status</Label>
                        <div className="mt-1">
                          <Badge
                            className="text-white"
                            variant={statusVariant[selectedReview.status]}
                          >
                            {statusLabel[selectedReview.status]}
                          </Badge>
                        </div>
                      </div>

                      <div>
                        <Label className="text-xs text-muted-foreground">Date</Label>
                        <p className="text-xs mt-0.5">
                          {formatDate(selectedReview.createdAt)}
                        </p>
                      </div>
                    </div>

                    {selectedReview.reviewDescription && (
                      <div>
                        <Label className="text-xs text-muted-foreground">Description</Label>
                        <p className="text-sm mt-1 bg-muted/40 p-3 rounded-md whitespace-pre-wrap">
                          <Interweave content={selectedReview.reviewDescription} />
                        </p>
                      </div>
                    )}

                    {selectedReview.images && selectedReview?.images?.length > 0 && (
                      <div>
                        <Label className="text-xs text-muted-foreground">Images</Label>
                        <div className="flex gap-2 flex-wrap mt-2">
                          {selectedReview.images && selectedReview?.images.map((img, i) => (
                            <img
                              key={i}
                              src={img}
                              alt={`Review image ${i + 1}`}
                              className="w-20 h-20 object-cover rounded-md border"
                            />
                          ))}
                        </div>
                      </div>
                    )}

                    

                  </div>
                  {/* Footer Actions */}
                  <div className="flex justify-end space-x-3 px-4 pb-3 pt-3 border-t -mx-2">
                    <Label className="text-xs text-muted-foreground self-center">
                      Quick action:
                    </Label>

                    {selectedReview.status !== 'approved' && (
                      <Button
                        size="sm"
                        onClick={() => {
                          handleStatusChange(selectedReview, 'approved');
                          setIsViewOpen(false);
                        }}
                        disabled={updatingStatus}
                      >
                        Approve
                      </Button>
                    )}

                    {selectedReview.status !== 'not-approved' && (
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => {
                          handleStatusChange(selectedReview, 'not-approved');
                          setIsViewOpen(false);
                        }}
                        disabled={updatingStatus}
                      >
                        Not approved
                      </Button>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      {/* Add/Edit Dialog */}
      <Dialog open={isEditOpen || isAddOpen} onOpenChange={(open) => {
        setIsEditOpen(open)
        setIsAddOpen(open)
      }}>
        <DialogContent className="max-w-2xl w-full max-h-[90vh] flex flex-col p-0">
          <div className="p-6 border-b">
            <DialogHeader>
              <DialogTitle>{isEditOpen ? 'Edit' : 'Add'} Review</DialogTitle>
            </DialogHeader>
          </div>
          <div className="p-4 pl-2 pr-2 pb-0 flex flex-col flex-1">
            <form onSubmit={handleSubmit} className="max-h-[60vh] min-h-[60vh] flex-1 pl-2 overflow-y-auto pr-2 pt-2 space-y-4 pb-4">
              <div className='flex flex-col gap-1'>
                <Label>Product</Label>
                <select
                  value={editForm.product}
                  onChange={(e) => setEditForm(p => ({ ...p, product: e.target.value }))}
                  className="px-3 py-2.5 rounded-md border border-input text-sm bg-white dark:bg-[#3B3B3B] focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-1 disabled:cursor-not-allowed disabled:opacity-50"
                  required
                >
                  {productsLoading ? (
                      <option value="">Loading...</option>
                  ) : (
                      <>
                      <option disabled value={''}>Select product</option>
                      {allProductOptions?.map((opt: any) => (
                          <option key={opt.value} value={opt.value}>{opt.label}</option>
                      ))}
                      </>
                  )}
                </select>
              </div>

              <div>
                <Label className="block mb-2">Review Title</Label>
                <Input
                  value={editForm.reviewTitle}
                  onChange={(e) => setEditForm(p => ({ ...p, reviewTitle: e.target.value }))}
                  required
                />
              </div>

              <div>
                <Label className="block mb-2">Description</Label>
                <Editor
                  rows={4}
                  value={editForm.reviewDescription}
                  onChange={(value:any) =>
                    setEditForm(prev => ({ ...prev, reviewDescription: value }))
                  }
                />
              </div>

              {/* Existing images */}
              {editForm.existingImages.length > 0 && (
              <div>
                  <Label className="block mb-2">Current Images</Label>
                  <div className="flex gap-2 flex-wrap mt-2">
                  {editForm.existingImages.map((url, i) => (
                      <div key={i} className="relative group">
                      <img
                          src={url}
                          alt={`Image ${i + 1}`}
                          className={`w-16 h-16 object-cover rounded-md border-2 transition-opacity ${
                          editForm.removedImages.includes(url) ? 'opacity-30' : 'opacity-100'
                          }`}
                      />
                      <button
                          type="button"
                          onClick={() => {
                          if (editForm.removedImages.includes(url)) {
                              // Undo remove
                              setEditForm(p => ({
                              ...p,
                              removedImages: p.removedImages.filter(r => r !== url)
                              }));
                          } else {
                              // Mark for removal
                              setEditForm(p => ({
                              ...p,
                              removedImages: [...p.removedImages, url]
                              }));
                          }
                          }}
                          className="absolute -top-1.5 -right-1.5 w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                      >
                          <X className="w-2.5 h-2.5" />
                      </button>
                      </div>
                  ))}
                  </div>
                  {editForm.removedImages.length > 0 && (
                  <p className="text-xs text-red-500 mt-1">
                      {editForm.removedImages.length} image(s) will be removed on save
                  </p>
                  )}
              </div>
              )}

              {/* Upload new images */}
              <div>
              <Label className="block mb-2">Add New Images</Label>
              <label className="flex items-center gap-2 mt-1.5 px-3 py-2 border border-dashed rounded-md cursor-pointer hover:bg-muted/40 transition-colors w-fit">
                  <Upload className="w-4 h-4 text-muted-foreground" />
                  <span className="text-sm text-muted-foreground">Choose images</span>
                  <input
                  type="file"
                  accept="image/*"
                  multiple
                  className="hidden"
                  onChange={(e) => {
                      const files = Array.from(e.target.files || []);
                      const valid = files.filter(f => {
                      if (f.size > 2 * 1024 * 1024) {
                          toast.error(`${f.name} exceeds 2MB`);
                          return false;
                      }
                      return true;
                      });
                      setEditForm(p => ({ ...p, newImages: [...p.newImages, ...valid] }));
                  }}
                  />
              </label>

              {/* New image previews */}
              {editForm.newImages.length > 0 && (
                  <div className="flex gap-2 flex-wrap mt-2">
                  {editForm.newImages.map((file, i) => (
                      <div key={i} className="relative group">
                      <img
                          src={URL.createObjectURL(file)}
                          alt={`New ${i + 1}`}
                          className="w-16 h-16 object-cover rounded-md border"
                      />
                      <button
                          type="button"
                          onClick={() => setEditForm(p => ({
                          ...p,
                          newImages: p.newImages.filter((_, idx) => idx !== i)
                          }))}
                          className="absolute -top-1.5 -right-1.5 w-4 h-4 rounded-full bg-red-500 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity"
                      >
                          <X className="w-2.5 h-2.5" />
                      </button>
                      <div className="absolute bottom-0 left-0 right-0 bg-black/50 text-white text-center rounded-b-md" style={{ fontSize: '9px' }}>
                          {Math.round(file.size / 1024)}KB
                      </div>
                      </div>
                  ))}
                  </div>
              )}
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label className="block mb-2">Rating</Label>
                  <select
                    value={editForm.rating}
                    onChange={(e) => setEditForm(p => ({ ...p, rating: parseInt(e.target.value) }))}
                    className="w-full mt-1 px-3 py-2 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-1 focus:ring-ring"
                  >
                    {[1, 2, 3, 4, 5].map(r => (
                      <option key={r} value={r}>{r} Star{r > 1 ? 's' : ''}</option>
                    ))}
                  </select>
                </div>
                {selectedReview?.status && <div>
                  <Label>Status</Label>
                  <select
                    value={editForm.status}
                    onChange={(e) => setEditForm(p => ({ ...p, status: e.target.value }))}
                    className="w-full mt-1 px-3 py-2 rounded-md border border-input bg-background text-sm focus:outline-none focus:ring-1 focus:ring-ring"
                  >
                    <option value="not-approved">Not-Approved</option>
                    <option value="approved">Approved</option>
                  </select>
                </div>}
              </div>

              <div className="flex justify-end gap-2 pt-1">
                  <Button type="button" variant="outline" onClick={() => { setIsEditOpen(false); setIsAddOpen(false) }}>Cancel</Button>
                  <Button 
                  type="submit" 
                  className="text-white" 
                  disabled={isSubmitting}
                  >
                  {isSubmitting ? (
                      <span className="flex items-center gap-2">
                      <svg className="animate-spin h-4 w-4" viewBox="0 0 24 24" fill="none">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"/>
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"/>
                      </svg>
                      {isEditOpen ? 'Updating...' : 'Adding...'}
                      </span>
                  ) : (
                      <>{isEditOpen ? 'Update' : 'Add'} Review</>
                  )}
                  </Button>
              </div>
            </form>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}