"use client";
import React, { useEffect, useState } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { useSearchParams } from "next/navigation";
import {
  ChevronDown,
  ChevronUp,
  Download,
  ImagePlus,
  Star,
  X,
} from "lucide-react";
import apis, { BUCKET_ROOT } from "@/utils/apis";
import Loader from "@/components/common/loader";
import dayjs from "dayjs";
import { currency } from "@/lib/utils";
import PaymentImg from "@/assets/images/Subtract.png";
import toast from "react-hot-toast";

const Summary = () => {
  const searchParams = useSearchParams();
  const id = searchParams.get("id");
  const [orderData, setorderData] = useState(null) as any;
  const [restaurantRating, setRestaurantRating] = useState(0);
  const [foodRating, setFoodRating] = useState(0);
  const [driverRating, setDriverRating] = useState(0);
  const [downloadLoading, setDownloadLoading] = useState(false);
  const [reviewDescription, setReviewDescription] = useState("");
  const [reviewImage, setReviewImage] = useState<string>("");
  const [imagePreview, setImagePreview] = useState<string>("");
  const [submitting, setSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);
  const [isAlreadyRated, setIsAlreadyRated] = useState(false);
  const [imageUploading, setImageUploading] = useState(false);
  const [showSurchargeDetails, setShowSurchargeDetails] = useState(false);
  const [showExtraChargeDetails, setShowExtraChargeDetails] = useState(false);

  const surchargeItems = (orderData?.surcharges || []).filter(
    (c: any) => c.charge_type === "surcharge" || c.surcharge_type === "surcharge" || (!c.charge_type && !c.surcharge_type && c.name?.toLowerCase().includes("rain"))
  );
  const extraChargeItems = (orderData?.surcharges || []).filter(
    (c: any) => c.charge_type === "extra_charge" || c.surcharge_type === "extra_charge" || (!c.charge_type && !c.surcharge_type && !c.name?.toLowerCase().includes("rain"))
  );

  const surchargeSum = surchargeItems.reduce((sum: number, c: any) => sum + (Number(c.value || c.amount) || 0), 0);
  const extraChargeSum = extraChargeItems.reduce((sum: number, c: any) => sum + (Number(c.value || c.amount) || 0), 0);

  const getOrderDetail = async (id: string) => {
    try {
      const apiRes = await apis.Orders.getDetail(id);
      setorderData(apiRes?.data);
      if (apiRes?.data?.restaurant_rating) {
        setRestaurantRating(apiRes?.data?.restaurant_rating);
      }
      if (apiRes?.data?.driver_rating) {
        setDriverRating(apiRes?.data?.driver_rating);
      }
    } catch (error) { }
  };

  useEffect(() => {
    if (id) {
      getOrderDetail(id);
    }
  }, [id]);

  // Prefill ratings when orderData is loaded and has existing ratings
  useEffect(() => {
    if (orderData) {
      // Get review data specifically for the restaurant
      const restaurantReview = orderData?.review?.find((r: any) => r.restaurant_id || r.restaurant);
      const existingRating = orderData?.restaurant_rating || restaurantReview?.rating;

      // Prefill restaurant rating - only if there's a valid rating > 0
      if (existingRating && Number(existingRating) > 0) {
        setRestaurantRating(Number(existingRating));
        setSubmitted(true);
        setIsAlreadyRated(true);
      }

      // Prefill food rating from restaurant review if available
      if (restaurantReview?.food_items?.[0]?.rate) {
        setFoodRating(parseInt(restaurantReview.food_items[0].rate) || 0);
      }

      // Prefill description from review
      if (restaurantReview?.description) {
        setReviewDescription(restaurantReview.description);
      }

      // Prefill image from review
      if (restaurantReview?.image) {
        setReviewImage(restaurantReview.image);
        setImagePreview(BUCKET_ROOT + restaurantReview.image);
      }
    }
  }, [orderData]);

  const handleInvoice = async () => {
    try {
      setDownloadLoading(true);
      const queryString = new URLSearchParams({ type: "customer" }).toString();
      const apiRes = await apis.Orders.invoice(id, queryString);
      const pdfUrl = apiRes?.data?.url || apiRes?.url;
      if (pdfUrl) {
        window.open(pdfUrl, "_blank");
      } else {
        console.error("No PDF URL found");
      }
    } catch (error) {
      console.error("Failed to download invoice", error);
    } finally {
      setDownloadLoading(false);
    }
  };

  const handleFoodRating = (rating: number) => {
    setFoodRating(rating);
  };

  const handleRestaurantRating = (rating: number) => {
    setRestaurantRating(rating);
  };

  const handleDriverRating = async (rating: number) => {
    try {
      setDriverRating(rating);
      let payload = {
        order_id: orderData?._id,
        driver_id: orderData?.driver?._id,
        rating: rating?.toString() || "0",
        description: "",
        image: "",
      };
      await apis.Review.driverRate(payload);
      if (id) {
        getOrderDetail(id);
      }
    } catch (error) { }
  };

  const handleImageUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Show preview
    const reader = new FileReader();
    reader.onloadend = () => {
      setImagePreview(reader.result as string);
    };
    reader.readAsDataURL(file);

    // Upload image
    try {
      setImageUploading(true);
      const apiRes = await apis.Common.uploadSingle("file", file);
      if (apiRes?.key) {
        setReviewImage(apiRes.key);
      } else {
        toast.error("Failed to upload image");
        setImagePreview("");
        setReviewImage("");
      }
    } catch (error) {
      console.error("Failed to upload image", error);
      toast.error("Failed to upload image");
      setImagePreview("");
      setReviewImage("");
    } finally {
      setImageUploading(false);
    }
  };

  const removeImage = () => {
    setReviewImage("");
    setImagePreview("");
    setImageUploading(false);
  };

  const handleSubmitReview = async () => {
    if (imageUploading) {
      toast.error("Please wait, image is still uploading...");
      return;
    }

    if (!restaurantRating && !foodRating) {
      toast.error("Please provide at least one rating");
      return;
    }

    try {
      setSubmitting(true);

      // If driver rating was selected but not submitted yet (rare but possible)
      if (orderData?.deliver_type === "driver" && driverRating > 0 && !orderData?.driver_rating) {
        try {
          await apis.Review.driverRate({
            order_id: orderData?._id,
            driver_id: orderData?.driver?._id,
            rating: driverRating?.toString(),
            description: "",
            image: "",
          });
        } catch (err) {
          console.error("Auto driver rating failed", err);
        }
      }

      let payload = {
        order_id: orderData?._id || id,
        restaurant_id: orderData?.restaurant?._id,
        food_items:
          (orderData?.other_cart_items?.length > 0 ? orderData?.other_cart_items : orderData?.cart_items)?.map((item: any) => ({
            food_id: item?.food_id || item?.item_id || item?._id,
            rate: foodRating?.toString() || "0",
          })) || [],
        rating: restaurantRating?.toString() || "0",
        description: reviewDescription,
        image: reviewImage,
      };

      const apiRes = await apis.Review.restaurantRate(payload);
      setRestaurantRating(apiRes?.data?.rating || restaurantRating);
      setSubmitted(true);
      toast.success("Feedback submitted successfully");
      if (id) {
        getOrderDetail(id);
      }
    } catch (error: any) {
      console.error("Review submission failed", error);
      toast.error(error?.response?.body?.message || "Failed to submit review");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="w-full p-6 bg-gray-50 min-h-screen">
      {/* Header */}
      <div className="flex justify-between items-center mb-2">
        <div>
          <div className="flex items-center gap-3">
            <h1 className="text-2xl font-bold text-gray-900">Order Summary</h1>
            {orderData?.order_status === "cancelled" && (
              <span className="bg-red-100 text-red-700 text-xs font-bold px-2.5 py-0.5 rounded-full border border-red-200">
                Cancelled
              </span>
            )}
          </div>
          <p className="text-gray-500 text-sm">Order ID: #{orderData?.order_id}</p>
        </div>
        <button
          onClick={handleInvoice}
          className="flex items-center gap-2 bg-brand-500 hover:bg-primary text-white px-4 py-2 rounded-lg transition-colors"
        >
          <Loader loading={downloadLoading} color="#fff" />
          <Download size={18} />
          <span>Download Receipt</span>
        </button>
      </div>

      {orderData?.order_status === "cancelled" && (
        <div className="bg-red-50 border-l-4 border-red-500 p-4 rounded-lg flex items-start gap-3 mt-4">
          <div className="text-red-500 mt-0.5">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor" className="w-5 h-5">
              <path strokeLinecap="round" strokeLinejoin="round" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
          </div>
          <div>
            <h3 className="font-semibold text-red-800 text-sm">Order Cancelled</h3>
            <p className="text-red-700 text-xs mt-1">
              This order has been cancelled. If any payment was processed, the refund will be credited back to your original source of payment within 5-7 business days.
            </p>
          </div>
        </div>
      )}

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 mt-6">
        {/* Left Column */}
        <div className="lg:col-span-7 space-y-6">
          {/* Order Details Card */}
          <div className="bg-white rounded-lg shadow-sm border-l-4 border-l-primary p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">Order Details</h2>

            {/* Restaurant Info */}
            <div className="flex items-center gap-3 mb-4 pb-4 border-b border-gray-100">
              <div className="w-12 h-12 rounded-lg overflow-hidden">
                <img
                  src={orderData?.restaurant?.image ? BUCKET_ROOT + orderData?.restaurant?.image : BUCKET_ROOT + orderData?.restaurant?.uploadRestaurantPhotos?.[0]}
                  alt="Restaurant"
                  className="w-full h-full object-cover"
                />
              </div>
              <div>
                <h3 className="font-semibold text-gray-900">{orderData?.restaurant?.restaurant_name}</h3>
                <p className="text-gray-500 text-sm">{orderData?.restaurant?.address?.area}</p>
              </div>
            </div>

            {/* Cart Items */}
            <div className="space-y-3">
              {(orderData?.other_cart_items?.length > 0 ? orderData?.other_cart_items : orderData?.cart_items)?.map((item: any, index: number) => {
                const variant = item?.quantity || item?.size || item?.pieces;
                return (
                  <div key={item.food_id || item.item_id || index} className="flex justify-between items-start py-2 border-b border-gray-50 last:border-b-0">
                    <div className="flex items-start gap-2">
                      <span className="text-gray-600 font-medium">{item.no_of_quantity} ×</span>
                      <div>
                        <span className="text-gray-800 font-medium">{item.name}</span>
                        {variant?.name && <p className="text-xs text-gray-500 mt-0.5">{variant.name}</p>}

                        {/* Display customizations */}
                        <div className="flex flex-wrap gap-1 mt-1">
                          {item?.add_ons?.map((add: any, idx: number) => (
                            <span key={idx} className="text-[10px] bg-gray-100 px-1 rounded text-gray-600">
                              {add.name}
                            </span>
                          ))}
                          {item?.toppings?.map((top: any, idx: number) => (
                            <span key={idx} className="text-[10px] bg-gray-100 px-1 rounded text-gray-600">
                              {top.name}
                            </span>
                          ))}
                          {item?.other_add_ons?.map((other: any, idx: number) => (
                            <span key={idx} className="text-[10px] bg-gray-100 px-1 rounded text-gray-600">
                              {other.name}
                            </span>
                          ))}
                        </div>

                        {/* Cooking Requests */}
                        {item?.cooking_req && (
                          <div className="mt-1.5">
                            <p className="text-neutral-900 text-[10px] font-semibold mb-0.5">
                              Cooking requests
                            </p>
                            <p className="text-gray-700 text-xs italic">
                              "{item.cooking_req}"
                            </p>
                          </div>
                        )}
                      </div>
                    </div>
                    <span className="font-medium text-gray-900 shrink-0">
                      {currency}
                      {Number(
                        item?.total_price ||
                        item?.priceQuantity ||
                        (parseFloat(item.price || 0) * (item.no_of_quantity || 0))
                      ).toFixed(2)}
                    </span>
                  </div>
                );
              })}
            </div>

            {/* Note for Restaurant & Receiver Details */}
            <div className="mt-4 pt-4 border-t border-gray-100">
              <div className="bg-gray-50 border-l-4 border-l-blue-400 p-4 rounded-r-lg space-y-2">
                <p className="text-gray-500 text-sm">Note for Vendor/Store: <span className="text-gray-700">{orderData?.note_for_restaurant || "N/A"}</span></p>
                <p className="text-gray-500 text-sm">
                  Receiver Details: <span className="text-gray-700">{orderData?.add_receiver_detail?.name}, {orderData?.add_receiver_detail?.country_code?.startsWith('+') ? '' : '+'}{orderData?.add_receiver_detail?.country_code} {orderData?.add_receiver_detail?.phone}</span>
                </p>
              </div>
            </div>
          </div>

          {/* Billing Details Card */}
          <div className="bg-white rounded-lg shadow-sm border-l-4 border-l-primary p-6">
            <h2 className="text-lg font-semibold text-gray-900 mb-4">Billing Details</h2>
            <div className="space-y-2">
              <p className="font-semibold text-gray-900">{orderData?.add_receiver_detail?.name}</p>
              <p className="text-gray-600 text-sm">{orderData?.add_receiver_detail?.country_code?.startsWith('+') ? '' : '+'}{orderData?.add_receiver_detail?.country_code} {orderData?.add_receiver_detail?.phone}</p>
              <p className="text-gray-600 text-sm">{orderData?.delivery_address?.name}</p>
              <p className="text-primary text-sm mt-3">
                {orderData?.order_status === "cancelled" ? (
                  `Cancelled on ${dayjs(orderData?.refund_at || orderData?.updated_at || orderData?.order_placed_at).format("DD MMM, YYYY")} at ${dayjs(orderData?.refund_at || orderData?.updated_at || orderData?.order_placed_at).format("hh:mm A")}`
                ) : (
                  `Delivered on ${dayjs(orderData?.order_delivered_at).format("DD MMM, YYYY")} at ${dayjs(orderData?.order_delivered_at).format("hh:mm A")}`
                )}
              </p>
            </div>
          </div>
        </div>

        {/* Right Column */}
        <div className="lg:col-span-5 space-y-6">
          {/* Delivery Partner Card */}
          {orderData?.deliver_type === "driver" && orderData?.order_status !== "cancelled" && (
            <div className="bg-white rounded-lg shadow-sm p-6">
              <div className="flex items-center gap-3 mb-4">
                <div className="w-12 h-12 rounded-lg overflow-hidden bg-gray-100">
                  {orderData?.driver?.image ? (
                    <img
                      src={BUCKET_ROOT + orderData?.driver?.image}
                      alt="Delivery Partner"
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-gray-400 text-xl font-semibold">
                      {orderData?.driver?.name?.charAt(0) || "D"}
                    </div>
                  )}
                </div>
                <div>
                  <h3 className="font-semibold text-gray-900">{orderData?.driver?.name || "Driver"}</h3>
                  <p className="text-gray-500 text-sm">Delivery Partner</p>
                </div>
              </div>

              <div className="border-t border-gray-100 pt-4 mb-4">
                <p className="text-gray-900 font-medium text-sm mb-1">Delivery Instructions</p>
                <p className="text-gray-500 text-sm">
                  {orderData?.add_delivery_instruction || "No instructions provided"}
                </p>
              </div>

              {/* Rate Delivery Partner */}
              <div>
                <p className="text-gray-900 font-medium text-sm mb-2">Rate your Delivery Partner</p>
                <div className="flex gap-1">
                  {[...Array(5)].map((_, i) => (
                    <Star
                      key={i}
                      size={20}
                      className={`transition-colors ${orderData?.driver_rating ? "cursor-default" : "cursor-pointer"}`}
                      fill={i < driverRating ? "hsl(var(--primary))" : "none"}
                      color={i < driverRating ? "hsl(var(--primary))" : "#D1D5DB"}
                      onClick={() => !orderData?.driver_rating && handleDriverRating(i + 1)}
                    />
                  ))}
                </div>
              </div>
            </div>
          )}

          <div className="w-full rounded-2xl p-6 text-white bg-black shadow-md flex flex-col gap-3">
            <h3 className="font-semibold text-sm mb-1 text-white">Payment</h3>
            <div className="space-y-1">
              {orderData?.deliver_type === "driver" && (
                <div className="flex justify-between text-xs text-white/90">
                  <span>Distance</span>
                  <span>{orderData?.distance}kms</span>
                </div>
              )}
              <div className="flex justify-between text-xs text-white/90">
                <span>Subtotal</span>
                <span>{currency}{orderData?.cart_amount}</span>
              </div>
              {orderData?.coupon_amount > 0 && (
                <div className="flex justify-between text-xs text-white/90">
                  <span>Coupon</span>
                  <span>-{currency}{orderData?.coupon_amount}</span>
                </div>
              )}
              {Number(orderData?.platform_fee || 0) > 0 && (
                <div className="flex justify-between text-xs text-white/90">
                  <span>Platform fee</span>
                  <span>{currency}{orderData?.platform_fee}</span>
                </div>
              )}
              {orderData?.tip_amount > 0 && (
                <div className="flex justify-between text-xs text-white/90">
                  <span>Driver Tip</span>
                  <span>{currency}{Number(orderData?.tip_amount)}</span>
                </div>
              )}
              {orderData?.deliver_type === "driver" && (
                <div className="flex justify-between text-xs text-white/90">
                  <span>Delivery fee</span>
                  <span>{currency}{Number(orderData?.delivery_fee).toFixed(2)}</span>
                </div>
              )}
              {Number(orderData?.tax_amount || 0) > 0 && (
                <div className="flex justify-between text-xs text-white/90">
                  <span>GST</span>
                  <span>{currency}{Number(orderData?.tax_amount).toFixed(2)}</span>
                </div>
              )}
              {surchargeSum > 0 && (
                <div className="flex flex-col gap-1 select-none">
                  <div
                    onClick={() => setShowSurchargeDetails(!showSurchargeDetails)}
                    className="flex justify-between items-center text-xs text-white/90 cursor-pointer hover:text-white transition-colors"
                  >
                    <span className="flex items-center gap-1.5">
                      Surcharges
                      {showSurchargeDetails ? <ChevronUp size={12} className="text-white/80" /> : <ChevronDown size={12} className="text-white/80" />}
                    </span>
                    <span className="font-semibold">{currency}{surchargeSum.toFixed(2)}</span>
                  </div>
                  {showSurchargeDetails && (
                    <div className="pl-3 pr-1 py-1 bg-white/10 rounded-lg flex flex-col gap-1 text-white/90">
                      {surchargeItems.map((charge: any) => (
                        <div key={charge._id || charge.name} className="flex justify-between items-center text-[10px]">
                          <span>{charge.name}</span>
                          <span>{currency}{Number(charge.value || charge.amount || 0).toFixed(2)}</span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}

              {extraChargeSum > 0 && (
                <div className="flex flex-col gap-1 select-none">
                  <div
                    onClick={() => setShowExtraChargeDetails(!showExtraChargeDetails)}
                    className="flex justify-between items-center text-xs text-white/90 cursor-pointer hover:text-white transition-colors"
                  >
                    <span className="flex items-center gap-1.5">
                      Extra Charges
                      {showExtraChargeDetails ? <ChevronUp size={12} className="text-white/80" /> : <ChevronDown size={12} className="text-white/80" />}
                    </span>
                    <span className="font-semibold">{currency}{extraChargeSum.toFixed(2)}</span>
                  </div>
                  {showExtraChargeDetails && (
                    <div className="pl-3 pr-1 py-1 bg-white/10 rounded-lg flex flex-col gap-1 text-white/90">
                      {extraChargeItems.map((charge: any) => (
                        <div key={charge._id || charge.name} className="flex justify-between items-center text-[10px]">
                          <span>{charge.name}</span>
                          <span>{currency}{Number(charge.value || charge.amount || 0).toFixed(2)}</span>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              )}
              {/* {orderData?.sales_commission > 0 && (
                <div className="flex justify-between text-xs text-white/90">
                  <span>Sales Commission</span>
                  <span>{currency}{Number(orderData?.sales_commission).toFixed(2)}</span>
                </div>
              )} */}
              <div className="w-full h-px border-t border-dashed border-t-white/30 my-0.5"></div>
              {((Number(orderData?.loyalty_point_redeemed) > 0) || (orderData?.promo_wallet_redeemed && Number(orderData?.promo_wallet_amount) > 0)) ? (
                <>
                  <div className="flex justify-between text-xs text-white/90">
                    <span>Total</span>
                    <span>{currency}{orderData?.total_amount?.toFixed(2)}</span>
                  </div>
                  {Number(orderData?.loyalty_point_redeemed) > 0 && (
                    <div className="flex justify-between text-xs text-white/90">
                      <span>Loyalty Discount</span>
                      <span>-{currency}{Number(orderData?.loyalty_point_redeemed).toFixed(2)}</span>
                    </div>
                  )}
                  {orderData?.promo_wallet_redeemed && Number(orderData?.promo_wallet_amount) > 0 && (
                    <div className="flex justify-between text-xs text-white/90">
                      <span>Promo Wallet Discount</span>
                      <span>-{currency}{Number(orderData?.promo_wallet_amount).toFixed(2)}</span>
                    </div>
                  )}
                  <div className="w-full h-px border-t border-dashed border-t-white/30 my-0.5"></div>
                  <div className="flex justify-between font-bold text-sm text-white">
                    <span>Payable Amount</span>
                    <span>{currency}{Math.max(0, (orderData?.total_amount || 0) - (Number(orderData?.loyalty_point_redeemed) || 0) - (Number(orderData?.promo_wallet_amount) || 0)).toFixed(2)}</span>
                  </div>
                </>
              ) : (
                <div className="flex justify-between font-semibold text-sm text-white">
                  <span>Total</span>
                  <span>{currency}{orderData?.total_amount?.toFixed(2)}</span>
                </div>
              )}
            </div>
          </div>

          {/* Add Feedback Card */}
          {orderData?.order_type !== "pos" && orderData?.order_status !== "pos" && (
            <div className="bg-white rounded-lg shadow-sm p-6">
              <h2 className="text-lg font-semibold text-gray-900 mb-4">Add Feedback</h2>

              {/* Food Rating */}
              <div className="mb-4">
                <p className="text-gray-600 text-sm mb-2">Food</p>
                <div className="flex gap-1">
                  {[...Array(5)].map((_, i) => (
                    <Star
                      key={i}
                      size={24}
                      className={`transition-colors ${isAlreadyRated ? "cursor-default" : "cursor-pointer"}`}
                      fill={i < foodRating ? "hsl(var(--primary))" : "none"}
                      color={i < foodRating ? "hsl(var(--primary))" : "#D1D5DB"}
                      onClick={() => !isAlreadyRated && handleFoodRating(i + 1)}
                    />
                  ))}
                </div>
              </div>

              {/* Restaurant Rating */}
              <div className="mb-4">
                <p className="text-gray-600 text-sm mb-2">Vendor/Store</p>
                <div className="flex gap-1">
                  {[...Array(5)].map((_, i) => (
                    <Star
                      key={i}
                      size={24}
                      className={`transition-colors ${isAlreadyRated ? "cursor-default" : "cursor-pointer"}`}
                      fill={i < restaurantRating ? "hsl(var(--primary))" : "none"}
                      color={i < restaurantRating ? "hsl(var(--primary))" : "#D1D5DB"}
                      onClick={() => !isAlreadyRated && handleRestaurantRating(i + 1)}
                    />
                  ))}
                </div>
              </div>

              {/* Review Text */}
              <div className="mb-4">
                <textarea
                  placeholder="Type comment..."
                  value={reviewDescription}
                  onChange={(e) => setReviewDescription(e.target.value)}
                  readOnly={isAlreadyRated}
                  className={`w-full border border-gray-200 rounded-lg p-3 text-sm resize-none h-20 focus:outline-none focus:ring-2 focus:ring-primary ${isAlreadyRated ? "bg-gray-50 cursor-not-allowed" : ""}`}
                />
              </div>

              {/* Add Image Button */}
              <div className="mb-4">
                {imagePreview ? (
                  <div className="relative inline-block">
                    <img
                      src={imagePreview}
                      alt="Review"
                      className={`w-24 h-24 object-cover rounded-lg ${imageUploading ? "opacity-50" : ""}`}
                    />
                    {imageUploading && (
                      <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/40 rounded-lg text-white text-xs gap-1">
                        <Loader loading={true} color="#fff" />
                        <span>Uploading...</span>
                      </div>
                    )}
                    {!isAlreadyRated && !imageUploading && (
                      <button
                        onClick={removeImage}
                        className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 shadow-sm"
                      >
                        <X size={14} />
                      </button>
                    )}
                  </div>
                ) : !isAlreadyRated ? (
                  <label className={`w-full flex items-center justify-center gap-2 bg-brand-500 hover:bg-primary text-white py-3 rounded-lg font-medium transition-colors ${imageUploading ? "opacity-70 cursor-not-allowed" : "cursor-pointer"}`}>
                    <input
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={handleImageUpload}
                      disabled={imageUploading}
                    />
                    {imageUploading ? (
                      <>
                        <Loader loading={true} color="#fff" />
                        <span>Uploading Image...</span>
                      </>
                    ) : (
                      <>
                        <ImagePlus size={20} />
                        <span>Add Image</span>
                      </>
                    )}
                  </label>
                ) : null}
              </div>

              {/* Submit Button */}
              {!isAlreadyRated && (
                <button
                  onClick={handleSubmitReview}
                  disabled={(!restaurantRating && !foodRating) || submitting || imageUploading}
                  className={`w-full py-3 rounded-lg font-medium transition-colors ${(restaurantRating || foodRating) && !submitting && !imageUploading
                    ? "bg-brand-500 text-white hover:bg-primary"
                    : "bg-gray-200 text-gray-500 cursor-not-allowed"
                    }`}
                >
                  {submitting ? (
                    <span className="flex items-center justify-center gap-2">
                      <Loader loading={true} color="#fff" />
                      Submitting...
                    </span>
                  ) : imageUploading ? (
                    <span className="flex items-center justify-center gap-2">
                      <Loader loading={true} color="#6B7280" />
                      Uploading Image...
                    </span>
                  ) : (
                    "Submit Review"
                  )}
                </button>
              )}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default function JobAutomationPage() {
  return (
    <DashboardLayout>
      <Summary />
    </DashboardLayout>
  );
}

