detail page connected to backend , modal form for one product connected to backend

This commit is contained in:
nabijonovdavronbek619@gmail.com
2026-02-07 14:36:11 +05:00
parent 74f1d7a9fd
commit 6a89bc1acc
11 changed files with 493 additions and 274 deletions

View File

@@ -1,10 +1,19 @@
"use client";
import { useTranslations } from "next-intl";
import Image from "next/image";
import { useState, useEffect } from "react";
import { X } from "lucide-react";
import { usePriceModalStore } from "@/store/useProceModalStore";
import { useMutation } from "@tanstack/react-query";
import httpClient from "@/request/api";
import { endPoints } from "@/request/links";
import { toast } from "react-toastify";
interface FormType {
name: string;
product: number;
phone: number; // ✅ String bo'lishi kerak
}
export function PriceModal() {
const t = useTranslations("priceModal");
@@ -13,31 +22,41 @@ export function PriceModal() {
const [formData, setFormData] = useState({
name: "",
phone: "+998 ",
captcha: "",
});
const [errors, setErrors] = useState({
name: "",
phone: "",
captcha: "",
});
const [captchaCode, setCaptchaCode] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
// Generate random captcha
useEffect(() => {
if (isOpen) {
const code = Math.random().toString(36).substring(2, 8).toUpperCase();
setCaptchaCode(code);
}
}, [isOpen]);
const formRequest = useMutation({
mutationFn: (data: FormType) =>
httpClient.post(endPoints.post.productContact, data),
onSuccess: () => {
setFormData({
name: "",
phone: "+998 ",
});
toast.success(t("success") || "Muvaffaqiyatli yuborildi!");
closeModal();
},
onError: (error) => {
console.error("Error:", error);
toast.error(t("error") || "Xatolik yuz berdi");
},
});
// Reset form when modal closes
useEffect(() => {
if (!isOpen) {
setFormData({ name: "", phone: "+998 ", captcha: "" });
setErrors({ name: "", phone: "", captcha: "" });
setFormData({
name: "",
phone: "+998 ",
});
setErrors({
name: "",
phone: "",
});
}
}, [isOpen]);
@@ -58,15 +77,14 @@ export function PriceModal() {
if (!numbers.startsWith("998")) {
return "+998 ";
}
let formatted = "+998 ";
const rest = numbers.slice(3);
if (rest.length > 0) formatted += rest.slice(0, 2);
if (rest.length > 2) formatted += " " + rest.slice(2, 5);
if (rest.length > 5) formatted += " " + rest.slice(5, 7);
if (rest.length > 7) formatted += " " + rest.slice(7, 9);
return formatted;
};
@@ -90,51 +108,45 @@ export function PriceModal() {
const newErrors = {
name: "",
phone: "",
captcha: "",
};
// Name validation
if (!formData.name.trim()) {
newErrors.name = t("validation.nameRequired");
newErrors.name = t("validation.nameRequired") || "Ism kiritilishi shart";
}
// Phone validation
const phoneNumbers = formData.phone.replace(/\D/g, "");
if (phoneNumbers.length !== 12) {
newErrors.phone = t("validation.phoneRequired");
newErrors.phone =
t("validation.phoneRequired") || "To'liq telefon raqam kiriting";
} else if (!phoneNumbers.startsWith("998")) {
newErrors.phone = t("validation.phoneInvalid");
}
if (!formData.captcha.trim()) {
newErrors.captcha = t("validation.captchaRequired");
} else if (formData.captcha.toUpperCase() !== captchaCode) {
newErrors.captcha = t("validation.captchaRequired");
newErrors.phone =
t("validation.phoneInvalid") || "Noto'g'ri telefon raqam";
}
setErrors(newErrors);
return !newErrors.name && !newErrors.phone && !newErrors.captcha;
return !newErrors.name && !newErrors.phone;
};
const handleSubmit = async (e: React.FormEvent) => {
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (!validateForm()) {
return;
}
setIsSubmitting(true);
// Telefon raqamni tozalash (faqat raqamlar)
const cleanPhone = formData.phone.replace(/\D/g, "");
try {
// API call logikangiz
await new Promise((resolve) => setTimeout(resolve, 1500));
const sendedData: FormType = {
name: formData.name,
phone: Number(cleanPhone), // ✅ String sifatida yuborish
product: product?.id || 0,
};
// Success
alert(t("success"));
closeModal();
} catch (error) {
alert(t("error"));
} finally {
setIsSubmitting(false);
}
console.log("Sended data:", sendedData);
formRequest.mutate(sendedData);
};
if (!isOpen || !product) return null;
@@ -143,49 +155,58 @@ export function PriceModal() {
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
{/* Backdrop */}
<div
className="absolute inset-0 bg-black/50"
className="absolute inset-0 bg-black/60 backdrop-blur-sm"
onClick={closeModal}
/>
{/* Modal */}
<div className="relative bg-white rounded-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto">
<div className="relative bg-[#2a2a2a] rounded-2xl shadow-2xl w-full max-w-md max-h-[90vh] overflow-y-auto">
{/* Close button */}
<button
onClick={closeModal}
className="absolute top-4 right-4 text-gray-400 hover:text-gray-600 transition-colors z-10"
className="absolute right-4 top-4 text-gray-400 hover:text-white transition-colors z-10"
aria-label="Close modal"
>
<X size={24} />
</button>
{/* Content */}
<div className="p-8">
<h2 className="text-3xl font-bold mb-8">{t("title")}</h2>
<div className="p-6 md:p-8">
<h2 className="text-2xl md:text-3xl font-bold text-white mb-6">
{t("title") || "Narx so'rash"}
</h2>
{/* Product Info */}
<div className="bg-[#f5f0e8] rounded-lg p-6 mb-8 flex items-center gap-6">
<div className="relative w-24 h-24 shrink-0">
<div className="bg-[#1e1e1e] rounded-lg p-4 mb-6 flex items-center gap-4">
<div className="relative w-20 h-20 shrink-0 bg-white rounded-lg overflow-hidden">
<Image
src={product.image}
src={product.image || "/placeholder.svg"}
alt={product.name}
fill
className="object-contain"
className="object-contain p-2"
/>
</div>
<div>
<h3 className="text-xl font-semibold mb-2">{product.name}</h3>
<span className="text-green-600 font-medium">
{t("product.inStock")}
<div className="flex-1">
<h3 className="text-white font-semibold mb-1 line-clamp-2">
{product.name}
</h3>
<span className="text-green-400 text-sm">
{product.inStock
? t("product.inStock") || "Sotuvda mavjud"
: t("product.outOfStock") || "Sotuvda yo'q"}
</span>
</div>
</div>
{/* Form */}
<form onSubmit={handleSubmit} className="space-y-6">
<form onSubmit={handleSubmit} className="space-y-5">
{/* Name */}
<div>
<label htmlFor="name" className="block text-sm font-medium mb-2">
{t("form.name")}
<label
htmlFor="name"
className="block text-sm font-medium text-gray-300 mb-2"
>
{t("form.name") || "Ismingiz"}
</label>
<input
type="text"
@@ -193,80 +214,50 @@ export function PriceModal() {
name="name"
value={formData.name}
onChange={handleInputChange}
placeholder={t("form.namePlaceholder")}
className={`w-full px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 ${
errors.name ? "border-red-500" : "border-gray-300"
}`}
className={`w-full px-4 py-3 bg-[#1e1e1e] border ${
errors.name ? "border-red-500" : "border-gray-700"
} rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-red-700 transition`}
placeholder={t("form.namePlaceholder") || "Ismingizni kiriting"}
/>
{errors.name && (
<p className="text-red-500 text-sm mt-1">{errors.name}</p>
<p className="mt-1 text-sm text-red-500">{errors.name}</p>
)}
</div>
{/* Phone */}
<div>
<label htmlFor="phone" className="block text-sm font-medium mb-2">
{t("form.phone")}
<label
htmlFor="phone"
className="block text-sm font-medium text-gray-300 mb-2"
>
{t("form.phone") || "Telefon raqam"}
</label>
<div className="relative">
<input
type="tel"
id="phone"
name="phone"
value={formData.phone}
onChange={handlePhoneChange}
placeholder={t("form.phonePlaceholder")}
className={`w-full pl-2 pr-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 ${
errors.phone ? "border-red-500" : "border-gray-300"
}`}
/>
</div>
<input
type="tel"
id="phone"
name="phone"
value={formData.phone}
onChange={handlePhoneChange}
className={`w-full px-4 py-3 bg-[#1e1e1e] border ${
errors.phone ? "border-red-500" : "border-gray-700"
} rounded-lg text-white placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-red-700 transition`}
placeholder="+998 90 123 45 67"
maxLength={17}
/>
{errors.phone && (
<p className="text-red-500 text-sm mt-1">{errors.phone}</p>
<p className="mt-1 text-sm text-red-500">{errors.phone}</p>
)}
</div>
{/* Captcha */}
{/* <div>
<label htmlFor="captcha" className="block text-sm font-medium mb-2">
{t("form.captcha")}
</label>
<div className="flex gap-4">
<div className="relative w-40 h-12 bg-linear-to-r from-purple-200 via-pink-200 to-blue-200 rounded-lg flex items-center justify-center">
<span className="text-2xl font-bold tracking-widest select-none">
{captchaCode}
</span>
<div className="absolute inset-0 opacity-30">
<svg className="w-full h-full">
<line x1="0" y1="0" x2="100%" y2="100%" stroke="currentColor" strokeWidth="1" />
<line x1="100%" y1="0" x2="0" y2="100%" stroke="currentColor" strokeWidth="1" />
</svg>
</div>
</div>
<input
type="text"
id="captcha"
name="captcha"
value={formData.captcha}
onChange={handleInputChange}
placeholder={t("form.captchaPlaceholder")}
className={`flex-1 px-4 py-3 border rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500 ${
errors.captcha ? "border-red-500" : "border-gray-300"
}`}
/>
</div>
{errors.captcha && (
<p className="text-red-500 text-sm mt-1">{errors.captcha}</p>
)}
</div> */}
{/* Submit Button */}
<button
type="submit"
disabled={isSubmitting}
className="w-full bg-[#8B1538] hover:bg-[#6d1028] text-white font-semibold py-4 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
disabled={formRequest.isPending}
className="w-full bg-red-700 hover:bg-red-800 disabled:bg-gray-600 disabled:cursor-not-allowed text-white font-bold py-3 px-6 rounded-lg transition-all duration-300 transform hover:scale-105 disabled:hover:scale-100"
>
{isSubmitting ? t("form.submitting") : t("form.submit")}
{formRequest.isPending
? t("form.submitting") || "Yuborilmoqda..."
: t("form.submit") || "Yuborish"}
</button>
</form>
</div>