'use client'; import { cart_api, OrderCreateBody } from '@/features/cart/lib/api'; import { orderForm } from '@/features/cart/lib/form'; 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 { zodResolver } from '@hookform/resolvers/zod'; import { Map, Placemark, Polygon, YMaps, ZoomControl, } from '@pbe/react-yandex-maps'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { Calendar as CalIcon, CheckCircle2, Clock, Loader2, LocateFixed, MapPin, User, } from 'lucide-react'; import { useTranslations } from 'next-intl'; import Image from 'next/image'; import { useEffect, useState } from 'react'; import { useForm } from 'react-hook-form'; import { toast } from 'sonner'; import z from 'zod'; import useOrderStore from '../lib/order'; const deliveryTimeSlots = [ { id: 1, label: '09:00 - 11:00', start: '09:00', end: '11:00' }, { id: 2, label: '11:00 - 13:00', start: '11:00', end: '13:00' }, { id: 3, label: '13:00 - 15:00', start: '13:00', end: '15:00' }, { id: 4, label: '15:00 - 17:00', start: '15:00', end: '17:00' }, { id: 5, label: '17:00 - 19:00', start: '17:00', end: '19:00' }, { id: 6, label: '19:00 - 21:00', start: '19:00', end: '21:00' }, ]; interface CoordsData { lat: number; lon: number; polygon: [number, number][][]; } const RefreshOrder = () => { const [deliveryDate, setDeliveryDate] = useState(); const [selectedTimeSlot, setSelectedTimeSlot] = useState(''); const { order: initialValues } = useOrderStore(); const t = useTranslations(); const queryClient = useQueryClient(); const initialCartItems = initialValues?.items.map((item) => ({ id: item.id, product_id: item.product.id, product_name: item.product.name, product_price: item.price, product_image: item.product.image || item.product.images?.[0]?.image || '/placeholder.svg', quantity: item.quantity, })); const cartItems = initialCartItems; const form = useForm>({ resolver: zodResolver(orderForm), defaultValues: { comment: initialValues?.comment, lat: '41.311081', long: '69.240562', }, }); const [orderSuccess, setOrderSuccess] = useState(false); const subtotal = cartItems ? cartItems.reduce( (sum, item) => sum + item.product_price * item.quantity, 0, ) : 0; const total = subtotal; const { mutate, isPending } = useMutation({ mutationFn: (body: OrderCreateBody) => cart_api.createOrder(body), onSuccess: () => { setOrderSuccess(true); queryClient.refetchQueries({ queryKey: ['cart_items'] }); }, onError: () => { toast.error('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); const getCoords = async (name: string): Promise => { 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, ) => { 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) => { if (!deliveryDate) { toast.error('Yetkazib berish sanasini tanlang', { richColors: true, position: 'top-center', }); return; } if (!selectedTimeSlot) { toast.error('Yetkazib berish vaqtini tanlang', { richColors: true, position: 'top-center', }); return; } if (initialValues === null) { toast.error('Savatcha bo‘sh', { richColors: true, position: 'top-center', }); return; } const items = initialValues.items.map((item) => ({ product_id: Number(item.product.id), quantity: item.quantity, })); mutate({ comment: value.comment, items: items, long: Number(value.long), lat: Number(value.lat), date: formatDate.format(deliveryDate, 'YYYY-MM-DD'), time: selectedTimeSlot, }); }; if (orderSuccess) { return (

{t('Buyurtma qabul qilindi!')}

{t('Buyurtmangiz muvaffaqiyatli qabul qilindi')}

); } return (
<> {/* Header */}

{t('Buyurtmani rasmiylashtirish')}

{t("Ma'lumotlaringizni to'ldiring")}

{/* Left Column - Forms */}
{/* Contact Information */}

{t("Shaxsiy ma'lumotlar")}

(