"use client";
import React, { useEffect, useState, useRef } from "react";
import { logEvent } from "@/utils/analytics";

import DashboardLayout from "@/components/layout/DashboardLayout";
import { useRouter } from "next/navigation";
import {
  ChevronRight,
  Clock,
  MapPin,
  Coins,
  Check,
  Bike,
  Store,
  Calendar,
  Utensils,
  FileText,
  User,
  Wallet2,
} from "lucide-react";
import CheckoutSlip from "@/components/checkoutSlip/page";
import FoodItemsContainer from "@/components/products/page";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch, RootState } from "@/store/store";
import { Modal } from "@/components/ui/modal";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { useGlobalContext } from "@/context/Provider";
import countries from "@/utils/CountryCode.json";
import CountryPickerModal from "@/components/countrycode/page";
import { Card } from "@/components/ui/card";
import apis from "@/utils/apis";
import CheckoutAddress from "@/components/checkoutAddress/page";
import { customerOrderDetail } from "@/store/actions/user/userAction";
import SchedulingComponent from "@/components/SchedulingComponent/page";
import { currency, formatDateTimeToUTC } from "@/lib/utils";

import AuthDrawer from "@/components/AuthDrawer/page";

const Checkout = () => {
  const { cartItems, orderDetail } = useSelector(
    (state: RootState) => state.user.profile
  );
  const router = useRouter();
  const { userInfo, setUserInfo, locationData } = useGlobalContext();
  const isLoggedIn = !!userInfo?.access_token;
  const dispatch: AppDispatch = useDispatch();
  const hasBegunCheckout = useRef(false);

  useEffect(() => {
    if (cartItems && cartItems.length > 0 && !hasBegunCheckout.current) {
      hasBegunCheckout.current = true;
      const checkoutValue = cartItems.reduce((acc: number, item: any) => acc + (parseFloat(item.priceQuantity || item.price || 0)), 0);
      logEvent("begin_checkout", {
        currency: "INR",
        value: checkoutValue,
        items: cartItems.map((item: any) => ({
          item_id: item.food_id || item.id,
          item_name: item.name || item.title,
          price: parseFloat(item.price || 0),
          quantity: item.no_of_quantity || item.quantity || 1,
          item_category: item.restaurant_type || "grocery"
        }))
      });
    }
  }, [cartItems]);

  useEffect(() => {
    if (typeof window !== "undefined") {
      (window as any).hasCompletedPurchase = false;
    }

    return () => {
      if (typeof window !== "undefined" && !(window as any).hasCompletedPurchase && hasBegunCheckout.current) {
        logEvent("checkout_abandoned", {
          cart_items_count: cartItems?.length || 0,
          value: cartItems?.reduce((acc: number, item: any) => acc + (parseFloat(item.priceQuantity || item.price || 0)), 0) || 0
        });
      }
    };
  }, []);
  const [deliveryOption, setDeliveryOption] = useState("now");
  const [value, setValue] = useState<any>(countries?.[97]);
  const [value1, setValue1] = useState<any>("");
  const [restroNote, setRestroNote] = useState("");
  const [deliveryNote, setDeliveryNote] = useState("");
  const [useLoyaltyPoints, setUseLoyaltyPoints] = useState(false);
  const [usePromoWallet, setUsePromoWallet] = useState(false);
  const [promoWalletBalance, setPromoWalletBalance] = useState(0);
  const [recieverName, setRecieverName] = useState("");
  const [configData, setConfigData] = useState(null) as any;
  const [couponList, setCouponList] = useState([]);
  const [surcharges, setSurcharges] = useState<any[]>([]);
  const [state, setState] = useState<any>("");
  const [isOpen, setIsOpen] = useState(false);
  const [isOpen2, setIsOpen2] = useState(false);
  const [isOpen3, setIsOpen3] = useState(false);
  const [isOpen4, setIsOpen4] = useState(false);
  const [isOpen5, setIsOpen5] = useState(false);

  const fetchSurcharges = async () => {
    try {
      const apiRes = await apis.Surcharge.getCurrentActive();
      if (apiRes) {
        const data = Array.isArray(apiRes) ? apiRes : (apiRes?.data || []);
        setSurcharges(data);
      }
    } catch (error) {
      console.error("Failed to fetch surcharges", error);
    }
  };

  const [tempRecieverName, setTempRecieverName] = useState("");
  const [tempState, setTempState] = useState<any>("");
  const [tempValue, setTempValue] = useState<any>(null);
  const [tempRestroNote, setTempRestroNote] = useState("");
  const [tempDeliveryNote, setTempDeliveryNote] = useState("");

  useEffect(() => {
    if (isOpen3) {
      setTempRecieverName(recieverName || userInfo?.name || "");
      setTempState(state || userInfo?.phone || "");
      setTempValue(value || { dial_code: userInfo?.country_code || "+91" });
    }
  }, [isOpen3, recieverName, state, value, userInfo]);

  useEffect(() => {
    if (isOpen) {
      setTempRestroNote(restroNote);
    }
  }, [isOpen, restroNote]);

  useEffect(() => {
    if (isOpen2) {
      setTempDeliveryNote(deliveryNote);
    }
  }, [isOpen2, deliveryNote]);
  const [isAuthDrawerOpen, setIsAuthDrawerOpen] = useState(false);
  const [addresses, setAddresses] = useState([]);
  const [locate] = useState({
    lat: 30.7069892,
    long: 76.6870682,
  });
  const [deliverType, setDeliverType] = useState("driver");
  const [restaurantType, setRestaurantType] = useState<string | null>(null);
  const [schedulingData, setSchedulingData] = useState<any>(null);
  const [hideDeliveryTime, setHideDeliveryTime] = useState(false);

  const [restaurantDetails, setRestaurantDetails] = useState<any>(null);

  useEffect(() => {
    if (typeof window !== "undefined") {
      const storedRestaurantType = localStorage.getItem("restaurant_type");
      setRestaurantType(storedRestaurantType);

      const resId = localStorage.getItem("restoId");
      if (resId) {
        apis.restaurant.detail(JSON.parse(resId), "")
          .then((res: any) => {
            if (res?.data) {
              setRestaurantDetails(res.data);
            }
          })
          .catch((err: any) => console.error("Error fetching restaurant details:", err));
      }
    }
  }, []);

  const isHomeCookedMeal = restaurantType === "home-cooked-meal";

  const [scheduledTime, setScheduledTime] = useState(() => {
    const now = new Date();
    const yyyy = now.getFullYear();
    const mm = String(now.getMonth() + 1).padStart(2, '0');
    const dd = String(now.getDate()).padStart(2, '0');
    const hh = String(now.getHours()).padStart(2, '0');
    const min = String(now.getMinutes()).padStart(2, '0');
    return `${yyyy}-${mm}-${dd}T${hh}:${min}`;
  });
  const [isScheduleModalOpen, setIsScheduleModalOpen] = useState(false);


  const configuration = async () => {
    try {
      const apiRes = await apis.Auth.configuration();
      setConfigData(apiRes?.data?.[0]);
    } catch (error) { }
  };

  const coupons = async () => {
    try {
      const resId = typeof window !== "undefined" && localStorage.getItem("restoId");
      let parsedRestoId = "";
      if (resId) {
        try {
          parsedRestoId = JSON.parse(resId);
        } catch (e) {
          parsedRestoId = resId;
        }
      }
      const query = parsedRestoId ? `restaurant_id=${parsedRestoId}` : "";
      const apiRes = await apis.Auth.coupon(query);
      setCouponList(apiRes?.data);
    } catch (error) { }
  };
  const getAdress = async () => {
    try {
      const apires = await apis.Profile.getAddress();
      if (apires) {
        setAddresses(apires?.data);
      }
    } catch (error) { }
  };

  const fetchPromoWalletBalance = async () => {
    try {
      const res = await apis.Wallet.getWalletBalance();
      setPromoWalletBalance(res?.data?.promo_balance || 0);
    } catch (error) {
      console.error("Error fetching promo balance:", error);
    }
  };

  useEffect(() => {
    configuration();
    coupons();
    fetchSurcharges();
    if (userInfo?.access_token) {
      getAdress();
      fetchPromoWalletBalance();
    }
  }, [userInfo?.access_token]);

  useEffect(() => {
    const resId: any = typeof window !== "undefined" && localStorage.getItem("restoId");
    if (cartItems?.length < 1) {
      if (typeof window !== "undefined" && (window as any).hasCompletedPurchase) {
        return;
      }
      localStorage.clear();
      router.push("/home");
      return;
    }
    const selectedAddress: any = userInfo?.current_address;

    const subTotalPrice =
      cartItems?.length > 0 &&
      cartItems.reduce((sum: any, item: any) => sum + parseFloat(item.priceQuantity), 0);
    const roundedSubTotal = subTotalPrice ? parseFloat(subTotalPrice.toFixed(2)) : 0;
    const salesCommission = 0;

    let data: Record<string, any> = {
      restaurant_id: JSON.parse(resId),
      cart_items: cartItems.map(({ cart_item_key, ...rest }: any) => rest),
      delivery_address: {
        "name": selectedAddress?.name || '',
        "lat": Number(selectedAddress?.lat) || Number(locationData?.lat),
        "long": Number(selectedAddress?.long) || Number(locationData?.lng),
        "building_no": selectedAddress?.building_no || '',
        "tower": selectedAddress?.tower || '',
        "area": selectedAddress?.area || '',
        "city": selectedAddress?.city || '',
        "nearby_landmark": selectedAddress?.nearby_landmark || '',
        "type": selectedAddress?.type || 'work'
      },
      note_for_restaurant: restroNote,
      add_delivery_instruction: deliveryNote,
      add_receiver_detail: {
        name: recieverName || userInfo?.name,
        phone: state || userInfo?.phone,
        country_code: value?.dial_code || userInfo?.country_code,
      },
      estimated_food_ready_time: 30,
      is_scheduled: deliveryOption === "now" ? false : true,
      scheduled_time:
        deliveryOption === "now"
          ? ""
          : formatDateTimeToUTC(scheduledTime),
      tip_amount: deliverType === "driver" ? Number(value1) : 0,
      deliver_type: deliverType,
      sales_commission: Number(salesCommission.toFixed(2)) || 0,
      ...(schedulingData || {}),
    };

    if (data) {
      dispatch(customerOrderDetail(data));
    }
  }, [
    deliveryNote,
    restroNote,
    recieverName,
    state,
    value1,
    cartItems,
    userInfo,
    deliverType,
    deliveryOption,
    scheduledTime,
    useLoyaltyPoints,
    usePromoWallet,
    schedulingData,
    configData
  ]);

  const handleCurrentAddress = async (data: any) => {
    try {
      const apiRes = await apis.Profile.addCurrentAddress(data?._id);
      if (apiRes) {
        setUserInfo((prev: any) => ({
          ...prev,
          current_address: data,
        }));
        setIsOpen5(false);
      }
    } catch (error) { }
  };
  const handleChange = (e: any) => {
    const newValue = e.target.value;

    if (newValue === "") {
      setValue1("");
      return;
    }

    if (newValue.includes("-") || Number(newValue) < 0) {
      return;
    }

    if (!isNaN(newValue) && newValue.length <= 3) {
      setValue1(newValue);
    }
  };

  const getMinimumScheduledTime = () => {
    const now = new Date();
    now.setMinutes(now.getMinutes() + 30);

    const rounded = new Date(Math.ceil(now.getTime() / (5 * 60 * 1000)) * (5 * 60 * 1000));
    const yyyy = rounded.getFullYear();
    const mm = String(rounded.getMonth() + 1).padStart(2, "0");
    const dd = String(rounded.getDate()).padStart(2, "0");
    const hh = String(rounded.getHours()).padStart(2, "0");
    const min = String(rounded.getMinutes()).padStart(2, "0");

    return `${yyyy}-${mm}-${dd}T${hh}:${min}`;
  };

  useEffect(() => {
    if (isScheduleModalOpen) {
      setScheduledTime(getMinimumScheduledTime());
    }
  }, [isScheduleModalOpen]);

  return (
    <div className="w-full p-6">
      <h2 className="text-2xl md:text-3xl font-bold mb-6">Order summary</h2>
      <div className="w-full h-auto grid grid-cols-1 lg:grid-cols-12 gap-8 max-w-7xl mx-auto">
        {/* Left Column - Main Content */}
        <div className="lg:col-span-8 w-full flex flex-col gap-6">

          {/* Account Section */}
          {!isLoggedIn && (
            <Card className="p-6 border-gray-100 shadow-sm relative overflow-hidden">
              <div className="flex justify-between items-start">
                <div className="w-full">
                  <h3 className="font-bold text-lg text-gray-900 mb-2">Account</h3>
                  <div>
                    <p className="text-gray-500 text-sm mb-6 max-w-md">
                      To place your order now, log in to your existing account or sign up.
                    </p>
                    <div className="flex flex-wrap gap-4">
                      <Button
                        variant="outline"
                        className="border-primary text-primary bg-transparent hover:bg-primary hover:!text-white px-8 rounded-none transition-all duration-200 shadow-none font-medium"
                        onClick={() => setIsAuthDrawerOpen(true)}
                      >
                        LOG IN
                      </Button>
                      <Button
                        className="bg-primary text-white hover:bg-primary/90 px-8 rounded-none transition-all duration-200 font-medium"
                        onClick={() => setIsAuthDrawerOpen(true)}
                      >
                        SIGN UP
                      </Button>
                    </div>
                  </div>
                </div>
                {/* Optional: Add an image here if available to match Swiggy's look */}
                {/* <div className="hidden md:block w-24 h-24 relative bg-gray-100 rounded-full"></div> */}
              </div>
            </Card>
          )}
          <AuthDrawer
            isOpen={isAuthDrawerOpen}
            onClose={() => setIsAuthDrawerOpen(false)}
          />

          {/* Address Section */}
          {deliverType === "takeaway" ? (
            <Card className="p-5 border-gray-100 shadow-sm hover:shadow-md transition-shadow">
              <div className="flex flex-col sm:flex-row justify-between items-start gap-4">
                <div className="flex gap-4">
                  <div className="w-10 h-10 rounded-full bg-brand-100 flex items-center justify-center text-primary shrink-0">
                    <Store size={20} />
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-900 text-lg">
                      Pickup Location ({restaurantDetails?.restaurant_name || "Restaurant"})
                    </h3>
                    <p className="text-gray-500 text-sm mt-1 max-w-md">
                      {restaurantDetails?.address?.name ||
                        [
                          restaurantDetails?.address?.building_no,
                          restaurantDetails?.address?.tower,
                          restaurantDetails?.address?.area,
                          restaurantDetails?.address?.city,
                        ]
                          .filter(Boolean)
                          .join(", ") ||
                        "Restaurant Address"}
                    </p>
                    <div className="flex items-center gap-2 mt-3 text-sm text-gray-600 bg-gray-50 w-fit px-3 py-1 rounded-full">
                      <Clock size={14} className="text-primary" />
                      <span>Prep Time: <span className="font-medium text-gray-900">{restaurantDetails?.average_preparing_time || 30} mins</span></span>
                    </div>
                  </div>
                </div>
              </div>
            </Card>
          ) : !isLoggedIn ? (
            <Card className="p-5 border-gray-100 shadow-sm bg-gray-50 opacity-70">
              <h3 className="font-semibold text-gray-500 text-lg">Delivery Address</h3>
            </Card>
          ) : (
            <Card className="p-5 border-gray-100 shadow-sm hover:shadow-md transition-shadow">
              <div className="flex flex-col sm:flex-row justify-between items-start gap-4">
                <div className="flex gap-4">
                  <div className="w-10 h-10 rounded-full bg-brand-100 flex items-center justify-center text-primary shrink-0">
                    <MapPin size={20} />
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-900 text-lg">
                      {(userInfo?.current_address?.type
                        ? userInfo.current_address.type.charAt(0).toUpperCase() + userInfo.current_address.type.slice(1)
                        : "Work")}
                    </h3>
                    <p className="text-gray-500 text-sm mt-1 max-w-md">
                      {userInfo?.current_address?.name || locationData?.address}
                    </p>
                    <div className="flex items-center gap-2 mt-3 text-sm text-gray-600 bg-gray-50 w-fit px-3 py-1 rounded-full">
                      <Clock size={14} className="text-primary" />
                      <span>Est. Time: <span className="font-medium text-gray-900">{restaurantDetails?.average_preparing_time || 30} mins</span></span>
                    </div>
                  </div>
                </div>
                <div className="flex gap-2 shrink-0 max-sm:ml-14">
                  <Button
                    variant="outline"
                    className="text-primary border-brand-200 hover:bg-brand-50 hover:text-primary"
                    onClick={() => router.push("/location")}
                  >
                    Add
                  </Button>
                  <Button
                    variant="outline"
                    className="text-primary border-brand-200 hover:bg-brand-50 hover:text-primary"
                    onClick={() => setIsOpen5(true)}
                  >
                    Change
                  </Button>
                </div>
              </div>
            </Card>
          )}

          {/* Other Sections - Only visible when logged in */}
          {isLoggedIn && (
            <>
              {/* Place Order On - Scheduling Component for Home Cooked Meals */}
              {isHomeCookedMeal && (
                <SchedulingComponent
                  onChange={(payload) => setSchedulingData(payload)}
                  onHideDeliveryTime={(shouldHide) => setHideDeliveryTime(shouldHide)}
                />
              )}

              {/* Delivery Options Grid */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {/* Delivery Type */}
                <Card className="p-5 border-gray-100 shadow-sm">
                  <h3 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
                    <Bike size={18} className="text-primary" />
                    Delivery Method
                  </h3>
                  <div className="grid grid-cols-2 gap-3">
                    <div
                      onClick={() => setDeliverType("driver")}
                      className={`cursor-pointer border rounded-xl p-3 flex flex-col items-center justify-center gap-2 transition-all ${deliverType === "driver"
                        ? "border-primary bg-brand-100 text-primary"
                        : "border-gray-200 hover:border-brand-200 text-gray-600"
                        }`}
                    >
                      <Bike size={24} />
                      <span className="text-sm font-medium">Delivery</span>
                    </div>
                    <div
                      onClick={() => setDeliverType("takeaway")}
                      className={`cursor-pointer border rounded-xl p-3 flex flex-col items-center justify-center gap-2 transition-all ${deliverType === "takeaway"
                        ? "border-primary bg-brand-100 text-primary"
                        : "border-gray-200 hover:border-brand-200 text-gray-600"
                        }`}
                    >
                      <Store size={24} />
                      <span className="text-sm font-medium">Takeaway</span>
                    </div>
                  </div>
                </Card>

                {/* Delivery Time - Hidden when home-cooked meal subscription is active */}
                <Card className="p-5 border-gray-100 shadow-sm">
                  <h3 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
                    <Clock size={18} className="text-primary" />
                    Delivery Time
                  </h3>
                  <div className="grid grid-cols-2 gap-3">
                    <div
                      onClick={() => setDeliveryOption("now")}
                      className={`cursor-pointer border rounded-xl p-3 flex flex-col items-center justify-center gap-2 transition-all ${deliveryOption === "now"
                        ? "border-primary bg-brand-50 text-primary"
                        : "border-gray-200 hover:border-brand-200 text-gray-600"
                        }`}
                    >
                      <Clock size={24} />
                      <span className="text-sm font-medium">Now</span>
                    </div>
                    <div
                      onClick={() => {
                        setDeliveryOption("later");
                        setIsScheduleModalOpen(true);
                      }}
                      className={`cursor-pointer border rounded-xl p-3 flex flex-col items-center justify-center gap-2 transition-all ${deliveryOption === "later"
                        ? "border-primary bg-brand-100 text-primary"
                        : "border-gray-200 hover:border-brand-200 text-gray-600"
                        }`}
                    >
                      <Calendar size={24} />
                      <span className="text-sm font-medium">Schedule</span>
                    </div>
                  </div>
                  {deliveryOption === "later" && scheduledTime && (
                    <div className="mt-3 text-xs text-center text-gray-500 bg-gray-50 py-1 rounded-lg">
                      Scheduled: <span className="font-medium text-gray-900">{new Date(scheduledTime).toLocaleString()}</span>
                    </div>
                  )}
                </Card>
              </div>

              {/* Products List */}
              <div className="flex flex-col gap-4">
                <h3 className="font-bold text-xl text-gray-900 flex items-center gap-2">
                  <Utensils size={20} className="text-primary" />
                  Your Items
                </h3>
                <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden">
                  <FoodItemsContainer data={cartItems} />
                </div>
              </div>

              {/* Additional Options (Notes, Receiver, Tips) */}
              <Card className="divide-y divide-gray-100 border-gray-100 shadow-sm overflow-hidden">

                {/* Note for Restaurant */}
                <div className="p-4 hover:bg-gray-50 transition-colors cursor-pointer" onClick={() => setIsOpen(true)}>
                  <div className="flex justify-between items-center">
                    <div className="flex items-center gap-3">
                      <div className="p-2 bg-gray-100 rounded-full text-gray-600">
                        <FileText size={18} />
                      </div>
                      <div>
                        <h4 className="text-sm font-medium text-gray-900">Note for Vendor/Store</h4>
                        <p className="text-xs text-gray-500 truncate max-w-[250px] md:max-w-md">
                          {restroNote || "Add special instructions for food..."}
                        </p>
                      </div>
                    </div>
                    <ChevronRight size={18} className="text-gray-400" />
                  </div>
                </div>

                {deliverType === "driver" && (
                  <>
                    {/* Delivery Instructions */}
                    <div className="p-4 hover:bg-gray-50 transition-colors cursor-pointer" onClick={() => setIsOpen2(true)}>
                      <div className="flex justify-between items-center">
                        <div className="flex items-center gap-3">
                          <div className="p-2 bg-gray-100 rounded-full text-gray-600">
                            <MapPin size={18} />
                          </div>
                          <div>
                            <h4 className="text-sm font-medium text-gray-900">Delivery Instructions</h4>
                            <p className="text-xs text-gray-500 truncate max-w-[250px] md:max-w-md">
                              {deliveryNote || "Add instructions for the driver..."}
                            </p>
                          </div>
                        </div>
                        <ChevronRight size={18} className="text-gray-400" />
                      </div>
                    </div>

                    {/* Receiver Details */}
                    <div className="p-4 hover:bg-gray-50 transition-colors cursor-pointer" onClick={() => setIsOpen3(true)}>
                      <div className="flex justify-between items-center">
                        <div className="flex items-center gap-3">
                          <div className="p-2 bg-gray-100 rounded-full text-gray-600">
                            <User size={18} />
                          </div>
                          <div>
                            <h4 className="text-sm font-medium text-gray-900">Receiver Details</h4>
                            <p className="text-xs text-gray-500">
                              {recieverName || userInfo?.name}, {(value?.dial_code || userInfo?.country_code)?.startsWith('+') ? '' : '+'}{value?.dial_code || userInfo?.country_code} {state || userInfo?.phone}
                            </p>
                          </div>
                        </div>
                        <ChevronRight size={18} className="text-gray-400" />
                      </div>
                    </div>

                    {/* Tip Section */}
                    <div className="p-5 bg-gray-50/50">
                      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                        <div>
                          <h4 className="text-sm font-medium text-gray-900">Tip your driver</h4>
                          <p className="text-xs text-gray-500">100% of the tip goes to your driver</p>
                        </div>
                        <div className="flex items-center gap-2">
                          {/* Preset Tips */}
                          {[10, 20, 50].map((amount) => (
                            <button
                              key={amount}
                              onClick={() => setValue1(amount)}
                              className={`px-3 py-1.5 text-sm font-medium rounded-lg border transition-all ${Number(value1) === amount
                                ? "bg-primary text-white border-primary"
                                : "bg-white text-gray-600 border-gray-200 hover:border-brand-200"
                                }`}
                            >
                              {currency}{amount}
                            </button>
                          ))}
                          {/* Custom Input */}
                          <div className="relative w-24">
                            <span className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-500 text-sm">{currency}</span>
                            <input
                              type="number"
                              min="0"
                              placeholder="Other"
                              value={value1}
                              onChange={handleChange}
                              onKeyDown={(e) => {
                                if (e.key === "-" || e.key === "e" || e.key === "E" || e.key === "+") {
                                  e.preventDefault();
                                }
                              }}
                              className="w-full pl-5 pr-2 py-1.5 text-sm border border-gray-200 rounded-lg focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                            />
                          </div>
                        </div>
                      </div>
                    </div>
                  </>
                )}
              </Card>
            </>
          )}

          {/* Payment Section - Placeholder for non-logged in users */}
          {!isLoggedIn && (
            <Card className="p-5 border-gray-100 shadow-sm bg-gray-50 opacity-70">
              <h3 className="font-semibold text-gray-500 text-lg">Payment</h3>
            </Card>
          )}
        </div>

        {/* Right Column - Summary & Loyalty */}
        <div className="lg:col-span-4 w-full flex flex-col gap-4">
          {userInfo?.loyalty_wallet?.balance > 0 && (
            <div className="w-full rounded-2xl bg-white shadow-sm border border-gray-100 overflow-hidden hover:shadow-md transition-all duration-300">
              <label className="relative flex items-center justify-between p-5 cursor-pointer group">
                {/* Active State Background */}
                <div
                  className={`absolute inset-0 bg-brand-50 transition-opacity duration-300 ${useLoyaltyPoints ? 'opacity-100' : 'opacity-0 group-hover:opacity-30'
                    }`}
                />

                <div className="flex items-center gap-4 relative z-10">
                  <div className={`
                    w-12 h-12 rounded-full flex items-center justify-center transition-all duration-300
                    ${useLoyaltyPoints ? 'bg-primary text-white shadow-primary/20 shadow-lg' : 'bg-brand-100 text-primary'}
                  `}>
                    <Coins size={24} />
                  </div>

                  <div className="flex flex-col">
                    <span className={`font-bold text-base transition-colors ${useLoyaltyPoints ? 'text-gray-900' : 'text-gray-700'}`}>
                      Use Loyalty Points
                    </span>
                    <span className="text-gray-500 text-xs font-medium">
                      Balance: {Number(userInfo?.loyalty_wallet?.balance ?? 0).toFixed(2)} pts
                    </span>
                  </div>
                </div>

                <div className="relative z-10 flex items-center">
                  <div className={`
                      w-6 h-6 rounded-md border-2 flex items-center justify-center transition-all duration-200
                      ${useLoyaltyPoints ? 'border-primary bg-primary' : 'border-gray-300 bg-white group-hover:border-primary'}
                   `}>
                    <Check size={16} className={`text-white transition-transform duration-200 ${useLoyaltyPoints ? 'scale-100' : 'scale-0'}`} strokeWidth={3} />
                  </div>
                  <input
                    type="checkbox"
                    checked={useLoyaltyPoints}
                    onChange={(e) => setUseLoyaltyPoints(e.target.checked)}
                    className="hidden"
                  />
                </div>
              </label>
            </div>
          )}

          {promoWalletBalance > 0 && (
            <div className="w-full rounded-2xl bg-white shadow-sm border border-gray-100 overflow-hidden hover:shadow-md transition-all duration-300">
              <label className="relative flex items-center justify-between p-5 cursor-pointer group">
                {/* Active State Background */}
                <div
                  className={`absolute inset-0 bg-brand-50 transition-opacity duration-300 ${usePromoWallet ? 'opacity-100' : 'opacity-0 group-hover:opacity-30'
                    }`}
                />

                <div className="flex items-center gap-4 relative z-10">
                  <div className={`
                    w-12 h-12 rounded-full flex items-center justify-center transition-all duration-300
                    ${usePromoWallet ? 'bg-primary text-white shadow-primary/20 shadow-lg' : 'bg-brand-100 text-primary'}
                  `}>
                    <Wallet2 size={24} />
                  </div>

                  <div className="flex flex-col">
                    <span className={`font-bold text-base transition-colors ${usePromoWallet ? 'text-gray-900' : 'text-gray-700'}`}>
                      Use Promo Wallet
                    </span>
                    <span className="text-gray-500 text-xs font-medium">
                      Balance: {currency}{Number(promoWalletBalance).toFixed(2)}
                    </span>
                  </div>
                </div>

                <div className="relative z-10 flex items-center">
                  <div className={`
                      w-6 h-6 rounded-md border-2 flex items-center justify-center transition-all duration-200
                      ${usePromoWallet ? 'border-primary bg-primary' : 'border-gray-300 bg-white group-hover:border-primary'}
                   `}>
                    <Check size={16} className={`text-white transition-transform duration-200 ${usePromoWallet ? 'scale-100' : 'scale-0'}`} strokeWidth={3} />
                  </div>
                  <input
                    type="checkbox"
                    checked={usePromoWallet}
                    onChange={(e) => setUsePromoWallet(e.target.checked)}
                    className="hidden"
                  />
                </div>
              </label>
            </div>
          )}

          <div className="sticky top-4">
            <CheckoutSlip
              data={configData}
              coupons={couponList}
              deliverType={deliverType}
              useLoyaltyPoints={useLoyaltyPoints}
              usePromoWallet={usePromoWallet}
              promoWalletBalance={promoWalletBalance}
              surcharges={surcharges}
            />
          </div>
        </div>
      </div>
      <Modal
        isOpen={isOpen}
        description=""
        onClose={() => setIsOpen(false)}
        title={"Add note for Vendor/Store"}
      >
        <div className="w-full flex flex-col gap-4">
          <Textarea
            className="w-full h-32 border border-gray-300 rounded-lg p-2"
            placeholder="Add note for Vendor/Store..."
            value={tempRestroNote}
            maxLength={225}
            onChange={(e) => setTempRestroNote(e.target.value)}
          ></Textarea>
          <Button
            className="bg-primary text-white py-2 px-4 rounded-lg"
            onClick={() => {
              setRestroNote(tempRestroNote);
              setIsOpen(false);
            }}
          >
            Save
          </Button>
        </div>
      </Modal>
      <Modal
        isOpen={isOpen2}
        description=""
        onClose={() => setIsOpen2(false)}
        title={"Add delivery instructions"}
      >
        <div className="w-full flex flex-col gap-4">
          <Textarea
            className="w-full h-32 border border-gray-300 rounded-lg p-2"
            placeholder="Add delivery instructions..."
            value={tempDeliveryNote}
            maxLength={150}
            onChange={(e) => setTempDeliveryNote(e.target.value)}
          ></Textarea>
          <Button
            className="bg-primary text-white py-2 px-4 rounded-lg"
            onClick={() => {
              setDeliveryNote(tempDeliveryNote);
              setIsOpen2(false);
            }}
          >
            Save
          </Button>
        </div>
      </Modal>
      <Modal
        isOpen={isOpen3}
        description=""
        onClose={() => setIsOpen3(false)}
        title={" Receiver Details"}
      >
        <div className="w-full flex flex-col gap-4">
          <input
            className="w-full h-12 border border-gray-300 rounded-lg p-2"
            placeholder="Add receiver name..."
            value={tempRecieverName}
            maxLength={15}
            onChange={(e) => setTempRecieverName(e.target.value)}
          />

          <div className="flex flex-row  w-full">
            <CountryPickerModal setValue={setTempValue} value={tempValue} />
            <input
              type="tel"
              placeholder="Enter mobile number"
              maxLength={15}
              value={tempState}
              onChange={(e: any) => setTempState(e.target.value)}
              className=" w-full border px-3 py-2 placeholder:text-[12px] rounded-md  focus:outline-none focus:bg-white-500 focus:ring-2 focus:ring-primary"
            />

          </div>
          <Button
            className="bg-primary text-white py-2 px-4 rounded-lg"
            onClick={() => {
              const finalName = tempRecieverName || userInfo?.name || "";
              const finalPhone = tempState || userInfo?.phone || "";
              const finalValue = tempValue?.dial_code ? tempValue : { dial_code: userInfo?.country_code || "+91" };
              setRecieverName(finalName);
              setState(finalPhone);
              setValue(finalValue);
              setIsOpen3(false);
            }}
          >
            Save
          </Button>
        </div>
      </Modal>
      {isOpen4 && (
        <CheckoutAddress
          title={"new address"}
          isOpen={isOpen4}
          setIsOpen={setIsOpen4}
          defaultCenter={{ lat: locate?.lat, lng: locate.long }}
        />
      )}
      <Modal
        isOpen={isOpen5}
        description=""
        onClose={() => setIsOpen5(false)}
        title={"Select Address"}
      >
        <div className="w-full flex flex-col gap-4 max-h-[50vh] overflow-y-auto no-scrollbar">
          {addresses?.length > 0 ?
            addresses?.map((item: any, index: number) => (
              <div
                key={item._id}
                className="border border-gray-200 rounded-lg p-4"
              >
                <div className="flex justify-between items-start mb-2">
                  <div className="flex items-center">
                    <div
                      className={`w-5 h-5 rounded-full mr-2 flex items-center justify-center ${userInfo?.current_address?._id === item?._id
                        ? "bg-primary"
                        : "border border-gray-300"
                        }`}
                      onClick={() => handleCurrentAddress(item)}
                    >
                      {userInfo?.current_address?._id === item?._id && (
                        <div className="w-2 h-2 rounded-full bg-white"></div>
                      )}
                    </div>
                    <span className="font-medium">{item.type ? item.type.charAt(0).toUpperCase() + item.type.slice(1) : ""}
                    </span>
                  </div>
                </div>
                <div className="pl-7 text-sm text-gray-600">{item?.name}</div>
              </div>
            )) : <div className="text-center text-gray-500 py-10">
              <p className="text-base font-medium">No address found</p>
              <p className="text-sm">Please add a new address to proceed.</p>
            </div>}
        </div>
      </Modal>
      <Modal
        isOpen={isScheduleModalOpen}
        onClose={() => setIsScheduleModalOpen(false)}
        title=""
        description=""
      >
        <div className="p-4 space-y-4">
          <h2 className="text-lg font-semibold">Schedule your delivery</h2>
          {/* Date Picker */}
          <input
            type="date"
            className="w-full border px-3 py-2 rounded"
            min={new Date().toISOString().split("T")[0]}
            max={new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString().split("T")[0]}
            value={scheduledTime.split("T")[0]}
            onChange={(e) => {
              const selectedDate = e.target.value;
              const time = scheduledTime.split("T")[1];
              setScheduledTime(`${selectedDate}T${time}`);
            }}
          />

          {/* Time Picker */}
          <input
            type="time"
            className="w-full border px-3 py-2 rounded"
            value={scheduledTime.split("T")[1]}
            min={(() => {
              const today = new Date().toISOString().split("T")[0];
              const selectedDate = scheduledTime.split("T")[0];

              if (selectedDate === today) {
                return getMinimumScheduledTime().split("T")[1];
              }
              return "00:00";
            })()}
            onChange={(e) => {
              const selectedTime = e.target.value;
              setScheduledTime(`${scheduledTime.split("T")[0]}T${selectedTime}`);
            }}
          />


          <Button
            className="w-full bg-primary hover:bg-primary/90 text-white font-semibold"
            onClick={() => setIsScheduleModalOpen(false)}
          >
            Confirm
          </Button>
        </div>
      </Modal>
    </div>
  );
};

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