'use client';

import { cart_api, OrderCreateBody } from '@/features/cart/lib/api';
import { orderForm } from '@/features/cart/lib/form';
import { BASE_URL } from '@/shared/config/api/URLs';
import formatDate from '@/shared/lib/formatDate';
import formatPrice from '@/shared/lib/formatPrice';
import { cn } from '@/shared/lib/utils';
import { Button } from '@/shared/ui/button';
import { Calendar } from '@/shared/ui/calendar';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from '@/shared/ui/form';
import { Input } from '@/shared/ui/input';
import { Label } from '@/shared/ui/label';
import { Popover, PopoverContent, PopoverTrigger } from '@/shared/ui/popover';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/shared/ui/select';
import { Textarea } from '@/shared/ui/textarea';
import { userStore } from '@/widgets/welcome/lib/hook';
import { zodResolver } from '@hookform/resolvers/zod';
import {
  Map,
  Placemark,
  Polygon,
  YMaps,
  ZoomControl,
} from '@pbe/react-yandex-maps';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import {
  Calendar as CalIcon,
  CheckCircle2,
  Clock,
  Loader2,
  LocateFixed,
  MapPin,
  Minus,
  Package,
  Plus,
  ShoppingBag,
  Trash2,
  User,
} from 'lucide-react';
import { useTranslations } from 'next-intl';
import Image from 'next/image';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { toast } from 'sonner';
import z from 'zod';
import OrderItem, { order_api } from '../lib/api';

const deliveryTimeSlots = [
  { id: 1, label: '10:00 - 12:00', start: '10:00', end: '12:00' },
  { id: 2, label: '12:00 - 14:00', start: '12:00', end: '14:00' },
  { id: 3, label: '14:00 - 16:00', start: '14:00', end: '16:00' },
  { id: 4, label: '16:00 - 18:00', start: '16:00', end: '18:00' },
];

interface CoordsData {
  lat: number;
  lon: number;
  polygon: [number, number][][];
}

const RefreshOrder = () => {
  const [deliveryDate, setDeliveryDate] = useState<Date>();
  const [selectedTimeSlot, setSelectedTimeSlot] = useState<string>('');
  const [orderItems, setOrderItems] = useState<OrderItem[]>([]);
  const { user } = userStore();
  const [quantityInputs, setQuantityInputs] = useState<Record<number, string>>(
    {},
  );

  const t = useTranslations();
  const queryClient = useQueryClient();
  const searchParams = useSearchParams();
  const router = useRouter();
  const id = searchParams.get('id');

  const { data, isLoading } = useQuery({
    queryKey: ['order_list'],
    queryFn: () => order_api.list(),
    select: (res) => res.data,
  });

  const initialValues = data?.find((e) => e.id === Number(id));

  useEffect(() => {
    if (initialValues?.items) {
      const items = initialValues.items.map((item: OrderItem) => ({ ...item }));
      setOrderItems(items);
      const inputs: Record<number, string> = {};
      items.forEach((item: OrderItem) => {
        inputs[item.id] = String(item.quantity);
      });
      setQuantityInputs(inputs);
    }
  }, [initialValues]);

  const form = useForm<z.infer<typeof orderForm>>({
    resolver: zodResolver(orderForm),
    defaultValues: {
      comment: initialValues?.comment || '',
      lat: '41.311081',
      long: '69.240562',
    },
  });

  useEffect(() => {
    if (initialValues?.comment) {
      form.setValue('comment', initialValues.comment);
    }
  }, [initialValues, form]);

  const [orderSuccess, setOrderSuccess] = useState(false);

  const { mutate, isPending } = useMutation({
    mutationFn: (body: OrderCreateBody) => cart_api.createOrder(body),
    onSuccess: () => {
      setOrderSuccess(true);
      queryClient.refetchQueries({ queryKey: ['cart_items'] });
      queryClient.refetchQueries({ queryKey: ['order_list'] });
    },
    onError: () => {
      toast.error(t('Xatolik yuz berdi'), {
        richColors: true,
        position: 'top-center',
      });
    },
  });

  const [coords, setCoords] = useState({
    latitude: 41.311081,
    longitude: 69.240562,
    zoom: 12,
  });
  const [polygonCoords, setPolygonCoords] = useState<
    [number, number][][] | null
  >(null);

  // Input o'zgarishi — foydalanuvchi "0.5", "1.75" yoza oladi
  const handleQuantityInput = (itemId: number, value: string) => {
    // Faqat raqam va nuqtaga ruxsat
    if (!/^(\d+\.?\d*)?$/.test(value)) return;
    setQuantityInputs((prev) => ({ ...prev, [itemId]: value }));

    const parsed = parseFloat(value);
    if (!isNaN(parsed) && parsed > 0) {
      setOrderItems((prev) =>
        prev.map((item) =>
          item.id === itemId ? { ...item, quantity: parsed } : item,
        ),
      );
    }
  };

  // Blur — bo'sh yoki 0 qiymatni 1 ga qaytarish
  const handleQuantityBlur = (itemId: number) => {
    const val = parseFloat(quantityInputs[itemId]);
    if (!val || val <= 0) {
      setQuantityInputs((prev) => ({ ...prev, [itemId]: '1' }));
      setOrderItems((prev) =>
        prev.map((item) =>
          item.id === itemId ? { ...item, quantity: 1 } : item,
        ),
      );
    }
  };

  // ± tugmalar — 0.5 qadamda o'zgartirish
  const updateQuantity = (itemId: number, delta: number) => {
    setOrderItems((prev) =>
      prev.map((item) => {
        if (item.id !== itemId) return item;
        const newQty = Math.max(
          0.5,
          Math.round((item.quantity + delta) * 100) / 100,
        );
        setQuantityInputs((inputs) => ({
          ...inputs,
          [itemId]: String(newQty),
        }));
        return { ...item, quantity: newQty };
      }),
    );
  };

  // Item o'chirish — agar 0 ta qolsa profile sahifaga yo'naltiradi
  const deleteItem = (itemId: number) => {
    const updated = orderItems.filter((item) => item.id !== itemId);
    setOrderItems(updated);
    if (updated.length === 0) {
      toast.info(t('Buyurtmada mahsulot qolmadi'), {
        richColors: true,
        position: 'top-center',
      });
      router.push('/profile');
    }
  };

  const getCoords = async (name: string): Promise<CoordsData | null> => {
    const res = await fetch(
      `https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(
        name,
      )}&format=json&polygon_geojson=1&limit=1`,
    );
    const data = await res.json();
    if (data.length > 0 && data[0].geojson) {
      const lat = parseFloat(data[0].lat);
      const lon = parseFloat(data[0].lon);
      let polygon: [number, number][][] = [];
      if (data[0].geojson.type === 'Polygon') {
        polygon = data[0].geojson.coordinates.map((ring: [number, number][]) =>
          ring.map((coord: [number, number]) => [coord[1], coord[0]]),
        );
      } else if (data[0].geojson.type === 'MultiPolygon') {
        polygon = data[0].geojson.coordinates.map(
          (poly: [number, number][][]) =>
            poly[0].map((coord: [number, number]) => [coord[1], coord[0]]),
        );
      }
      return { lat, lon, polygon };
    }
    return null;
  };

  const handleMapClick = (
    e: ymaps.IEvent<MouseEvent, { coords: [number, number] }>,
  ) => {
    const [lat, lon] = e.get('coords');
    setCoords({ latitude: lat, longitude: lon, zoom: 18 });
    form.setValue('lat', lat.toString(), { shouldDirty: true });
    form.setValue('long', lon.toString(), { shouldDirty: true });
  };

  const handleShowMyLocation = () => {
    if (!navigator.geolocation) {
      alert("Sizning brauzeringiz geolokatsiyani qo'llab-quvvatlamaydi");
      return;
    }
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const lat = position.coords.latitude;
        const lon = position.coords.longitude;
        setCoords({ latitude: lat, longitude: lon, zoom: 14 });
        form.setValue('lat', lat.toString());
        form.setValue('long', lon.toString());
      },
      (error) => {
        alert('Joylashuv aniqlanmadi: ' + error.message);
      },
    );
  };

  const cityValue = form.watch('city');

  useEffect(() => {
    if (!cityValue || cityValue.length < 3) return;
    const timeout = setTimeout(async () => {
      const result = await getCoords(cityValue);
      if (!result) return;
      setCoords({ latitude: result.lat, longitude: result.lon, zoom: 12 });
      setPolygonCoords(result.polygon);
      form.setValue('lat', result.lat.toString(), { shouldDirty: true });
      form.setValue('long', result.lon.toString(), { shouldDirty: true });
    }, 700);
    return () => clearTimeout(timeout);
  }, [cityValue]);

  const onSubmit = (value: z.infer<typeof orderForm>) => {
    if (!deliveryDate) {
      toast.error(t('Yetkazib berish sanasini tanlang'), {
        richColors: true,
        position: 'top-center',
      });
      return;
    }

    if (!selectedTimeSlot) {
      toast.error(t('Yetkazib berish vaqtini tanlang'), {
        richColors: true,
        position: 'top-center',
      });
      return;
    }

    if (!initialValues) {
      toast.error(t('Buyurtma topilmadi'), {
        richColors: true,
        position: 'top-center',
      });
      return;
    }

    const order_products = orderItems
      .filter(
        (item) =>
          item.product.prices &&
          item.product.prices.length > 0 &&
          item.product.prices[0].price_type?.code &&
          item.product.prices[0].price,
      )
      .map((item) => ({
        inventory_kind: 'G',
        product_code: item.product.code,
        on_balance: 'Y',
        order_quant: item.quantity,
        price_type_code: item.product.prices![0].price_type.code,
        product_price: item.price,
        warehouse_code: process.env.NEXT_PUBLIC_WARHOUSES_CODE!,
      }));
    if (user) {
      const dealTime = formatDate.format(deliveryDate, 'DD.MM.YYYY');

      mutate({
        order: [
          {
            filial_code: process.env.NEXT_PUBLIC_FILIAL_CODE!,
            delivery_date: `${dealTime}`,
            room_code: process.env.NEXT_PUBLIC_ROOM_CODE!,
            deal_time: formatDate.format(new Date(), 'DD.MM.YYYY'),
            robot_code: process.env.NEXT_PUBLIC_ROBOT_CODE!,
            status: 'D',
            sales_manager_code: process.env.NEXT_PUBLIC_SALES_MANAGER_CODE!,
            person_code: user?.username,
            currency_code: '860',
            owner_person_code: user?.username,
            note: value.comment,
            order_products: order_products,
          },
        ],
      });
    } else {
      toast.error(t('Xatolik yuz berdi'), {
        richColors: true,
        position: 'top-center',
      });
    }
  };

  const totalPrice = orderItems.reduce(
    (sum, item) => sum + Number(item.price) * item.quantity,
    0,
  );

  const totalItems = orderItems.reduce((sum, item) => sum + item.quantity, 0);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-screen">
        <Loader2 className="w-12 h-12 animate-spin text-blue-600" />
      </div>
    );
  }

  if (!initialValues) {
    return (
      <div className="flex flex-col items-center justify-center h-screen">
        <Package className="w-20 h-20 text-gray-400 mb-4" />
        <h2 className="text-2xl font-bold text-gray-800 mb-2">
          {t('Buyurtma topilmadi')}
        </h2>
        <p className="text-gray-500 mb-6">
          {t("Ushbu buyurtma mavjud emas yoki o'chirilgan")}
        </p>
        <Button onClick={() => (window.location.href = '/profile/history')}>
          {t('Buyurtmalar tarixiga qaytish')}
        </Button>
      </div>
    );
  }

  if (orderSuccess) {
    return (
      <div className="flex justify-center items-center h-screen">
        <div className="bg-white rounded-lg shadow-lg p-8 max-w-md w-full text-center">
          <div className="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
            <CheckCircle2 className="w-12 h-12 text-green-600" />
          </div>
          <h2 className="text-2xl font-bold text-gray-800 mb-2">
            {t('Buyurtma qabul qilindi!')}
          </h2>
          <p className="text-gray-500 mb-6">
            {t('Buyurtmangiz muvaffaqiyatli qayta qabul qilindi')}
          </p>
          <button
            onClick={() => (window.location.href = '/')}
            className="w-full bg-blue-600 text-white py-3 rounded-lg font-semibold hover:bg-blue-700 transition"
          >
            {t('Bosh sahifaga qaytish')}
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="custom-container mb-5">
      <>
        {/* Header */}
        <div className="mb-6">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">
            {t('Buyurtmani qayta rasmiylashtirish')}
          </h1>
          <p className="text-gray-600">
            {t('Buyurtma')} #{initialValues.id}{' '}
            {t("uchun ma'lumotlarni yangilang")}
          </p>
        </div>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)}>
            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
              {/* Left Column - Forms */}
              <div className="lg:col-span-2 space-y-6">
                {/* Contact Information */}
                <div className="bg-white rounded-lg shadow-md p-6">
                  <div className="flex items-center gap-2 mb-4">
                    <User className="w-5 h-5 text-blue-600" />
                    <h2 className="text-xl font-semibold">
                      {t("Shaxsiy ma'lumotlar")}
                    </h2>
                  </div>

                  <FormField
                    control={form.control}
                    name="comment"
                    render={({ field }) => (
                      <FormItem>
                        <Label className="block mt-3 text-sm font-medium text-gray-700">
                          {t('Izoh')}
                        </Label>
                        <FormControl>
                          <Textarea
                            {...field}
                            maxLength={300}
                            className="w-full min-h-42 max-h-64 border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:border-blue-500"
                            placeholder={t('Izoh')}
                          />
                        </FormControl>
                        <div className="text-right text-xs text-gray-500">
                          {field.value?.length || 0}/300
                        </div>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>

                <div className="bg-white rounded-lg shadow-md p-6">
                  <div className="flex items-center gap-2 mb-4">
                    <MapPin className="w-5 h-5 text-blue-600" />
                    <h2 className="text-xl font-semibold">
                      {t('Yetkazib berish manzili')}
                    </h2>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <FormField
                      control={form.control}
                      name="city"
                      render={({ field }) => (
                        <FormItem>
                          <Label className="block text-sm font-medium text-gray-700">
                            {t('Manzilni qidirish')}
                          </Label>
                          <FormControl>
                            <Input
                              {...field}
                              type="text"
                              className="w-full border h-12 border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:border-blue-500"
                              placeholder={t('Toshkent')}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <div className="md:col-span-2">
                      <div className="relative h-80 border rounded-lg overflow-hidden">
                        <YMaps query={{ lang: 'en_RU' }}>
                          <Map
                            key={`${coords.latitude}-${coords.longitude}`}
                            state={{
                              center: [coords.latitude, coords.longitude],
                              zoom: coords.zoom,
                            }}
                            width="100%"
                            height="100%"
                            onClick={handleMapClick}
                          >
                            <ZoomControl
                              options={{
                                position: { right: '10px', bottom: '70px' },
                              }}
                            />
                            <Placemark
                              geometry={[coords.latitude, coords.longitude]}
                            />
                            {polygonCoords && (
                              <Polygon
                                geometry={polygonCoords}
                                options={{
                                  fillColor: 'rgba(0, 150, 255, 0.2)',
                                  strokeColor: 'rgba(0, 150, 255, 0.8)',
                                  strokeWidth: 2,
                                  interactivityModel: 'default#transparent',
                                }}
                              />
                            )}
                          </Map>
                        </YMaps>
                        <Button
                          type="button"
                          size="sm"
                          onClick={handleShowMyLocation}
                          className="absolute bottom-3 right-2.5 shadow-md bg-white text-black hover:bg-gray-100"
                        >
                          <LocateFixed className="w-4 h-4 mr-1" />
                          {t('Mening joylashuvim')}
                        </Button>
                      </div>
                    </div>
                  </div>
                </div>

                {/* Yetkazib berish vaqti */}
                <div className="bg-white rounded-lg shadow-md p-6">
                  <div className="flex items-center gap-2 mb-4">
                    <Clock className="w-5 h-5 text-blue-600" />
                    <h2 className="text-xl font-semibold">
                      {t('Yetkazib berish vaqti')}
                    </h2>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    {/* Sana tanlash */}
                    <div className="space-y-2">
                      <Label className="block text-sm font-medium text-gray-700">
                        {t('Yetkazib berish sanasi')}
                      </Label>
                      <Popover>
                        <PopoverTrigger asChild>
                          <Button
                            type="button"
                            variant="outline"
                            className={cn(
                              'w-full h-12 justify-start text-left font-normal',
                              !deliveryDate && 'text-muted-foreground',
                            )}
                          >
                            <CalIcon className="mr-2 h-4 w-4" />
                            {deliveryDate ? (
                              formatDate.format(deliveryDate, 'DD-MM-YYYY')
                            ) : (
                              <span>{t('Sanani tanlang')}</span>
                            )}
                          </Button>
                        </PopoverTrigger>
                        <PopoverContent className="w-auto p-0" align="start">
                          <Calendar
                            mode="single"
                            selected={deliveryDate}
                            captionLayout="dropdown"
                            toYear={new Date().getFullYear() + 10}
                            onSelect={setDeliveryDate}
                            disabled={(date) =>
                              date < new Date() ||
                              date < new Date(new Date().setHours(0, 0, 0, 0))
                            }
                            initialFocus
                          />
                        </PopoverContent>
                      </Popover>
                    </div>

                    {/* Vaqt tanlash */}
                    <div className="space-y-2">
                      <Label className="block text-sm font-medium text-gray-700">
                        {t("Vaqt oralig'i")}
                      </Label>
                      <Select
                        value={selectedTimeSlot}
                        onValueChange={setSelectedTimeSlot}
                      >
                        <SelectTrigger className="w-full !h-12">
                          <SelectValue placeholder={t('Vaqtni tanlang')} />
                        </SelectTrigger>
                        <SelectContent>
                          {deliveryTimeSlots.map((slot) => (
                            <SelectItem key={slot.id} value={slot.label}>
                              <div className="flex items-center gap-2">
                                <Clock className="w-4 h-4 text-gray-500" />
                                {slot.label}
                              </div>
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>

                  {/* Tanlangan vaqt ko'rinishi */}
                  {deliveryDate && selectedTimeSlot && (
                    <div className="mt-4 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                      <div className="flex items-start gap-3">
                        <div className="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
                          <CalIcon className="w-5 h-5 text-blue-600" />
                        </div>
                        <div>
                          <p className="font-semibold text-gray-800">
                            {t('Tanlangan yetkazib berish vaqti')}
                          </p>
                          <p className="text-sm text-gray-600 mt-1">
                            {formatDate.format(deliveryDate, 'DD-MM-YYYY')} |{' '}
                            {selectedTimeSlot}
                          </p>
                        </div>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              {/* Right Column - Order Summary */}
              <div className="lg:col-span-1">
                <div className="bg-white rounded-lg shadow-md p-6 sticky top-4">
                  <div className="flex items-center gap-2 mb-4">
                    <ShoppingBag className="w-5 h-5 text-blue-600" />
                    <h3 className="text-xl font-bold">
                      {t('Buyurtma tafsilotlari')}
                    </h3>
                  </div>

                  {/* Cart Items */}
                  <div className="space-y-3 mb-4 max-h-96 overflow-y-auto">
                    {orderItems.map((item) => {
                      const productImage = item.product.images?.[0]?.images
                        ? item.product.images[0].images.includes(BASE_URL)
                          ? item.product.images[0].images
                          : BASE_URL + item.product.images[0].images
                        : '/placeholder.svg';

                      return (
                        <div
                          key={item.id}
                          className="flex gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200"
                        >
                          <div className="w-16 h-16 flex-shrink-0 bg-white rounded-lg overflow-hidden border">
                            <Image
                              src={productImage}
                              alt={item.product.name}
                              width={64}
                              height={64}
                              className="w-full h-full object-contain"
                              unoptimized
                            />
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="flex items-start justify-between gap-1">
                              <h4 className="font-semibold text-sm text-gray-900 truncate">
                                {item.product.name}
                              </h4>
                              {/* O'chirish tugmasi */}
                              <button
                                type="button"
                                onClick={() => deleteItem(item.id)}
                                className="flex-shrink-0 w-6 h-6 flex items-center justify-center rounded-full text-red-400 hover:text-red-600 hover:bg-red-50 transition"
                                title={t("O'chirish")}
                              >
                                <Trash2 className="w-8 h-8" />
                              </button>
                            </div>
                            <p className="text-sm font-bold text-blue-600 mt-1">
                              {formatPrice(
                                Number(item.price) * item.quantity,
                                true,
                              )}
                            </p>

                            {/* Quantity — input + ± tugmalar */}
                            <div className="flex items-center gap-1 mt-2">
                              <button
                                type="button"
                                onClick={() => updateQuantity(item.id, -1)}
                                className="w-7 h-7 max-lg:w-10 max-lg:h-10 flex items-center justify-center rounded-full border border-gray-300 bg-white hover:bg-gray-100 transition"
                              >
                                <Minus className="w-3 h-3 max-lg:w-4 max-lg:h-4" />
                              </button>
                              <input
                                type="text"
                                inputMode="decimal"
                                value={quantityInputs[item.id] ?? item.quantity}
                                onChange={(e) =>
                                  handleQuantityInput(item.id, e.target.value)
                                }
                                onBlur={() => handleQuantityBlur(item.id)}
                                className="w-14 h-7 max-lg:w-24 max-lg:h-10 text-center text-sm font-semibold border border-gray-300 rounded-md focus:outline-none focus:border-blue-500"
                              />
                              <button
                                type="button"
                                onClick={() => updateQuantity(item.id, 1)}
                                className="w-7 h-7 max-lg:w-10 max-lg:h-10 flex items-center justify-center rounded-full border border-gray-300 bg-white hover:bg-gray-100 transition"
                              >
                                <Plus className="w-3 h-3 max-lg:w-4 max-lg:h-4" />
                              </button>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>

                  {/* Pricing */}
                  <div className="space-y-2 mb-4 pt-4 border-t">
                    <div className="flex justify-between text-gray-600">
                      <span>{t('Mahsulotlar soni')}:</span>
                      <span className="font-semibold">
                        {totalItems} {t('dona')}
                      </span>
                    </div>
                    <div className="flex justify-between text-gray-600">
                      <span>{t('Mahsulotlar narxi')}:</span>
                      <span className="font-semibold">
                        {formatPrice(totalPrice, true)}
                      </span>
                    </div>
                  </div>

                  <div className="border-t pt-4 mb-6">
                    <div className="flex justify-between items-center">
                      <span className="text-lg font-semibold">
                        {t('Jami')}:
                      </span>
                      <span className="text-2xl font-bold text-green-600">
                        {formatPrice(totalPrice, true)}
                      </span>
                    </div>
                  </div>

                  <button
                    type="submit"
                    disabled={isPending}
                    className="w-full bg-blue-600 text-white py-4 rounded-lg font-semibold hover:bg-blue-700 transition disabled:bg-gray-400 disabled:cursor-not-allowed"
                  >
                    {isPending ? (
                      <span className="flex items-center justify-center gap-2">
                        <Loader2 className="animate-spin" />
                        {t('Yuklanmoqda...')}
                      </span>
                    ) : (
                      t('Buyurtmani tasdiqlash')
                    )}
                  </button>
                </div>
              </div>
            </div>
          </form>
        </Form>
      </>
    </div>
  );
};

export default RefreshOrder;
