"use client"; import React, { useState } from "react"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { Icon } from "@/components/ui/icon"; import { useTranslations } from "next-intl"; import { ProfileFormProps, RegistrationFormData, InstituteData, registrationSchema, } from "@/types/registration"; import { useLocationData, useInstituteData, useRegistration, } from "@/hooks/use-registration"; import dynamic from "next/dynamic"; const PasswordChecklist = dynamic(() => import("react-password-checklist"), { ssr: false, }); import Swal from "sweetalert2"; import withReactContent from "sweetalert2-react-content"; const MySwal = withReactContent(Swal); export const ProfileForm: React.FC = ({ userData, category, onSuccess, onError, className, }) => { const t = useTranslations("LandingPage"); const { submitRegistration, loading: submitLoading } = useRegistration(); const { provinces, cities, districts, fetchCities, fetchDistricts, loading: locationLoading, } = useLocationData(); const { institutes, saveInstitute, loading: instituteLoading, } = useInstituteData(Number(category)); const [selectedProvince, setSelectedProvince] = useState(""); const [selectedCity, setSelectedCity] = useState(""); const [selectedDistrict, setSelectedDistrict] = useState(""); const [selectedInstitute, setSelectedInstitute] = useState(""); const [isCustomInstitute, setIsCustomInstitute] = useState(false); const [customInstituteName, setCustomInstituteName] = useState(""); const [instituteAddress, setInstituteAddress] = useState(""); const [password, setPassword] = useState(""); const [passwordConf, setPasswordConf] = useState(""); const [showPassword, setShowPassword] = useState(false); const [showPasswordConf, setShowPasswordConf] = useState(false); const [usernameTouched, setUsernameTouched] = useState(false); const [otpIdentity, setOtpIdentity] = useState<{ email: string; nrp?: string; personelName?: string; }>({ email: "", }); const { register, handleSubmit, formState: { errors, isSubmitting }, setValue, watch, } = useForm({ resolver: zodResolver(registrationSchema), mode: "onChange", defaultValues: { email: userData }, }); React.useEffect(() => { const stored = sessionStorage.getItem("registration_identity"); if (stored) { const parsed = JSON.parse(stored); setOtpIdentity({ email: parsed.email, nrp: parsed.nrp, personelName: parsed.personelName, }); // default nama dari API if (parsed.personelName) { setValue("firstName", parsed.personelName); const autoUsername = parsed.personelName .toLowerCase() .trim() .replace(/\s+/g, "-") .replace(/[^a-z0-9-]/g, ""); setValue("username", autoUsername); } setValue("email", parsed.email); } }, [setValue]); const watchedPassword = watch("password"); const handleProvinceChange = (provinceId: string) => { setSelectedProvince(provinceId); setSelectedCity(""); setSelectedDistrict(""); setValue("kota", ""); setValue("kecamatan", ""); if (provinceId) { fetchCities(provinceId); } }; const handleCityChange = (cityId: string) => { setSelectedCity(cityId); setSelectedDistrict(""); setValue("kecamatan", ""); if (cityId) { fetchDistricts(cityId); } }; const handleDistrictChange = (districtId: string) => { setSelectedDistrict(districtId); setValue("kecamatan", districtId); }; const handleInstituteChange = (instituteId: string) => { setSelectedInstitute(instituteId); setIsCustomInstitute(instituteId === "0"); }; const handlePasswordChange = (value: string) => { setPassword(value); setValue("password", value); }; const handlePasswordConfChange = (value: string) => { setPasswordConf(value); setValue("passwordConf", value); }; const togglePasswordVisibility = () => { setShowPassword(!showPassword); }; const togglePasswordConfVisibility = () => { setShowPasswordConf(!showPasswordConf); }; // const onSubmit = async (data: RegistrationFormData) => { // try { // let instituteId = 1; // // Handle custom institute for journalists // if (category === "6" && isCustomInstitute) { // if (!customInstituteName.trim() || !instituteAddress.trim()) { // onError?.("Please fill in all institute details"); // return; // } // const instituteData: InstituteData = { // id: "0", // name: customInstituteName, // address: instituteAddress, // }; // instituteId = await saveInstitute(instituteData); // } else if (category === "6" && selectedInstitute) { // instituteId = Number(selectedInstitute); // } // const success = await submitRegistration( // data, // category, // userData, // instituteId // ); // if (success) { // onSuccess?.(data); // } // } catch (error: any) { // onError?.(error.message || "Registration failed"); // } // }; const onSubmit = async (data: RegistrationFormData) => { // 🔹 TAMPILKAN LOADING MySwal.fire({ title: "Processing", text: "Pleasewait", allowOutsideClick: false, allowEscapeKey: false, didOpen: () => { Swal.showLoading(); }, }); try { let instituteId = 1; // default (non-journalist / personel) // khusus journalist if (category === "6") { if (isCustomInstitute) { if (!customInstituteName.trim() || !instituteAddress.trim()) { Swal.close(); onError?.("Please fill in all institute details"); return; } const instituteData: InstituteData = { id: "0", name: customInstituteName, address: instituteAddress, }; instituteId = await saveInstitute(instituteData); } else if (selectedInstitute) { instituteId = Number(selectedInstitute); } } const payload = { ...data, email: otpIdentity.email, nrp: otpIdentity.nrp, personelName: otpIdentity.personelName, }; const success = await submitRegistration( payload, category, otpIdentity.email, instituteId ); // 🔹 TUTUP LOADING Swal.close(); if (success) { sessionStorage.removeItem("registration_identity"); await Swal.fire({ icon: "success", title:"Success", text: "Register Success !!", confirmButtonColor: "#dc3545", }); onSuccess?.(payload); } } catch (error: any) { // 🔹 TUTUP LOADING Swal.close(); Swal.fire({ icon: "error", title: "Failed", text: error?.message || "Registration failed", confirmButtonColor: "#dc3545", }); onError?.(error.message || "Registration failed"); } }; const renderInstituteFields = () => { if (category !== "6") return null; return (
{isCustomInstitute && ( <>
setCustomInstituteName(e.target.value)} />