"use client"; import { district_api } from "@/features/district/lib/api"; import { object_api } from "@/features/object/lib/api"; import type { CreatePharmacyReq } from "@/features/phamarcy/lib/data"; import formatPhone from "@/shared/lib/formatPhone"; import onlyNumber from "@/shared/lib/onlyNumber"; import { Button } from "@/shared/ui/button"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/shared/ui/form"; import { Input } from "@/shared/ui/input"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/shared/ui/select"; import { DashboardLayout } from "@/widgets/dashboard-layout/ui/DashboardLayout"; import { zodResolver } from "@hookform/resolvers/zod"; import { Circle, Map, Placemark, Polygon, YMaps, ZoomControl, } from "@pbe/react-yandex-maps"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { AxiosError } from "axios"; import { Loader2, LocateFixed } from "lucide-react"; import { useRef, useState } from "react"; import { useForm } from "react-hook-form"; import { useNavigate } from "react-router-dom"; import { toast } from "sonner"; import z from "zod"; import { pharmacy_api } from "../lib/api"; import { objectForm } from "../lib/form"; interface CoordsData { lat: number; lon: number; polygon: [number, number][][]; } const CreatePharmacy = () => { const queryClinent = useQueryClient(); const router = useNavigate(); const mapRef = useRef(null); const form = useForm>({ resolver: zodResolver(objectForm), defaultValues: { districts: "", name: "", inn: "", phoneDirector: "+998", phonePharmacy: "+998", }, }); const { mutate, isPending } = useMutation({ mutationFn: (body: CreatePharmacyReq) => pharmacy_api.create(body), onSuccess: () => { router("/pharmacy"); queryClinent.refetchQueries({ queryKey: ["pharmacy_list"] }); }, onError: (error: AxiosError) => { const data = error.response?.data as { message?: string }; const errorData = error.response?.data as { messages?: { token_class: string; token_type: string; message: string; }[]; }; const errorName = error.response?.data as { data?: { name: string[]; }; }; toast.error( errorName.data?.name[0] || data.message || errorData?.messages?.[0].message || "Xatolik yuz berdi", ); }, }); const { data: districts } = useQuery({ queryKey: ["my_disctrict"], queryFn: () => district_api.getDiscrict(), select(data) { return data.data.data; }, }); const district_id = form.watch("districts"); const { data: streets } = useQuery({ queryKey: ["object_list", district_id], queryFn: () => object_api.getAll({ district_id: Number(district_id) }), select(data) { return data.data.data; }, }); const [coords, setCoords] = useState({ latitude: 41.311081, longitude: 69.240562, }); 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 [polygonCoords, setPolygonCoords] = useState< [number, number][][] | null >(null); const [circleCoords, setCircleCoords] = useState<[number, number] | null>( null, ); const handleStreetChange = (streetId: string) => { form.setValue("streets", streetId); const selectedStreet = streets?.find((s) => s.id === Number(streetId)); if (!selectedStreet) return; setCoords({ latitude: selectedStreet.latitude, longitude: selectedStreet.longitude, }); form.setValue("latitude", selectedStreet.latitude); form.setValue("longitude", selectedStreet.longitude); setCircleCoords([selectedStreet.latitude, selectedStreet.longitude]); if (mapRef.current) { mapRef.current.setCenter( [selectedStreet.latitude, selectedStreet.longitude], 16, ); } }; 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 }); form.setValue("latitude", lat); form.setValue("longitude", lon); if (mapRef.current) { mapRef.current.setCenter([lat, lon], 20); } }, (error) => { alert("Joylashuv aniqlanmadi: " + error.message); }, ); }; const handleMapClick = ( e: ymaps.IEvent, ) => { const [lat, lon] = e.get("coords"); setCoords({ latitude: lat, longitude: lon }); form.setValue("latitude", lat); form.setValue("longitude", lon); }; const onSubmit = (values: z.infer) => { mutate({ district_id: Number(values.districts), extra_location: { latitude: values.latitude, longitude: values.longitude, }, inn: values.inn, latitude: values.latitude, longitude: values.longitude, name: values.name, owner_phone: onlyNumber(values.phoneDirector), place_id: Number(values.streets), responsible_phone: onlyNumber(values.phonePharmacy), }); }; return (

{"Qo'shish"}

( Nomi )} /> ( INN )} /> ( Dorixona egasining nomeri { const formatted = formatPhone(e.target.value); field.onChange(formatted); }} /> )} /> ( Mas’ul shaxsning nomeri { const formatted = formatPhone(e.target.value); field.onChange(formatted); }} /> )} /> ( Tuman )} /> ( {"Ko'cha"} )} /> ( Xarita
{polygonCoords && ( )} {circleCoords && ( )}
)} />
); }; export default CreatePharmacy;