"use client"; import React, { useState, useEffect } from "react"; import { useForm, Controller } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import * as z from "zod"; import { Card, CardHeader, CardTitle, CardContent, CardFooter, } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { Checkbox } from "@/components/ui/checkbox"; import Swal from "sweetalert2"; import withReactContent from "sweetalert2-react-content"; import { errorAutoClose, loading, successAutoClose } from "@/lib/swal"; import { close } from "@/config/swal"; import Image from "next/image"; import { getClientProfile, updateClientProfile, uploadClientLogo, ClientProfile } from "@/service/client/client-profile"; import { SaveIcon } from "@/components/icons"; // ✅ Zod Schema Validasi const companySchema = z.object({ companyName: z.string().trim().min(1, "Nama perusahaan wajib diisi"), address: z.string().trim().min(1, "Alamat perusahaan wajib diisi"), phone: z .string() .regex(/^[0-9+\-\s]+$/, "Nomor telepon tidak valid") .min(6, "Nomor telepon minimal 6 karakter"), website: z .string() .url("Masukkan URL website yang valid") .optional() .or(z.literal("")), description: z.string().trim().optional(), isActive: z.boolean().default(true), logo: z.any().optional(), }); type CompanySchema = z.infer; interface TenantCompanyUpdateFormProps { id: number; initialData?: any; onSuccess?: () => void; onCancel?: () => void; } export default function TenantCompanyUpdateForm({ id, initialData, onSuccess, onCancel, }: TenantCompanyUpdateFormProps) { const MySwal = withReactContent(Swal); const [previewLogo, setPreviewLogo] = useState(null); const [loadingData, setLoadingData] = useState(false); const [clientProfile, setClientProfile] = useState(null); const [selectedLogoFile, setSelectedLogoFile] = useState(null); const { control, handleSubmit, setValue, formState: { errors }, watch, } = useForm({ resolver: zodResolver(companySchema), defaultValues: { companyName: "", address: "", phone: "", website: "", description: "", isActive: true, }, }); // ✅ Load data awal dari server useEffect(() => { async function fetchCompanyData() { setLoadingData(true); try { const response = await getClientProfile(); if (response?.data?.success && response.data.data) { const data = response.data.data; setClientProfile(data); // Set form values setValue("companyName", data.name || ""); setValue("address", data.address || ""); setValue("phone", data.phoneNumber || ""); setValue("website", data.website || ""); setValue("description", data.description || ""); setValue("isActive", data.isActive ?? true); setPreviewLogo(data.logoUrl || null); } } catch (err: any) { console.error("❌ Gagal memuat data perusahaan:", err); errorAutoClose(err?.message || "Gagal memuat data perusahaan"); } finally { setLoadingData(false); } } fetchCompanyData(); }, [setValue]); // ✅ Fungsi Upload Logo const handleLogoChange = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; if (!file.type.startsWith("image/")) { MySwal.fire({ icon: "error", title: "Format tidak valid", text: "File harus berupa gambar (jpg, png, webp, dll)", }); return; } // Validasi ukuran file (max 5MB) if (file.size > 5 * 1024 * 1024) { MySwal.fire({ icon: "error", title: "Ukuran file terlalu besar", text: "Ukuran file maksimal 5MB", }); return; } setValue("logo", file); setSelectedLogoFile(file); setPreviewLogo(URL.createObjectURL(file)); }; // ✅ Fungsi Remove Logo const handleRemoveLogo = () => { setValue("logo", undefined); setSelectedLogoFile(null); setPreviewLogo(clientProfile?.logoUrl || null); }; // ✅ Submit Form const onSubmit = async (data: CompanySchema) => { try { loading(); // Update profile data terlebih dahulu const updateData = { name: data.companyName, address: data.address, phoneNumber: data.phone, website: data.website || undefined, description: data.description || undefined, }; console.log("📦 Payload:", updateData); const response = await updateClientProfile(updateData); if (response?.data?.success) { // Jika ada logo yang dipilih, upload logo if (selectedLogoFile) { try { console.log("📤 Uploading logo..."); const logoResponse = await uploadClientLogo(selectedLogoFile); if (logoResponse?.data?.success) { console.log("✅ Logo uploaded successfully"); } else { console.warn("⚠️ Logo upload failed, but profile updated"); } } catch (logoError: any) { console.error("❌ Error uploading logo:", logoError); // Tidak menghentikan proses jika logo gagal diupload } } close(); successAutoClose("Data perusahaan berhasil diperbarui."); setTimeout(() => { if (onSuccess) onSuccess(); }, 2000); } else { close(); errorAutoClose("Gagal memperbarui data perusahaan."); } } catch (err: any) { close(); console.error("❌ Gagal update perusahaan:", err); errorAutoClose(err?.message || "Terjadi kesalahan saat memperbarui data perusahaan."); } }; if (loadingData) { return (

Memuat data perusahaan...

); } return (
Update Informasi Perusahaan {/* Logo Upload */}
{previewLogo && (
Company Logo
{selectedLogoFile && ( )}
)}

Format yang didukung: JPG, PNG, WebP. Maksimal 5MB.

{/* Nama Perusahaan */}
( )} /> {errors.companyName && (

{errors.companyName.message}

)}
{/* Alamat */}
(