kontenhumas-fe/components/form/tenant/tenant-detail-update-form.tsx

375 lines
11 KiB
TypeScript
Raw Normal View History

2025-10-11 10:07:14 +00:00
"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";
2025-10-11 10:07:14 +00:00
// ✅ 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<typeof companySchema>;
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<string | null>(null);
const [loadingData, setLoadingData] = useState(false);
const [clientProfile, setClientProfile] = useState<ClientProfile | null>(null);
const [selectedLogoFile, setSelectedLogoFile] = useState<File | null>(null);
2025-10-11 10:07:14 +00:00
const {
control,
handleSubmit,
setValue,
formState: { errors },
watch,
} = useForm<CompanySchema>({
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);
2025-10-11 10:07:14 +00:00
}
} catch (err: any) {
2025-10-11 10:07:14 +00:00
console.error("❌ Gagal memuat data perusahaan:", err);
errorAutoClose(err?.message || "Gagal memuat data perusahaan");
2025-10-11 10:07:14 +00:00
} finally {
setLoadingData(false);
}
}
fetchCompanyData();
}, [setValue]);
2025-10-11 10:07:14 +00:00
// ✅ Fungsi Upload Logo
const handleLogoChange = (e: React.ChangeEvent<HTMLInputElement>) => {
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;
}
2025-10-11 10:07:14 +00:00
setValue("logo", file);
setSelectedLogoFile(file);
2025-10-11 10:07:14 +00:00
setPreviewLogo(URL.createObjectURL(file));
};
// ✅ Fungsi Remove Logo
const handleRemoveLogo = () => {
setValue("logo", undefined);
setSelectedLogoFile(null);
setPreviewLogo(clientProfile?.logoUrl || null);
};
2025-10-11 10:07:14 +00:00
// ✅ 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,
};
2025-10-11 10:07:14 +00:00
console.log("📦 Payload:", updateData);
2025-10-11 10:07:14 +00:00
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
}
}
2025-10-11 10:07:14 +00:00
close();
successAutoClose("Data perusahaan berhasil diperbarui.");
setTimeout(() => {
if (onSuccess) onSuccess();
}, 2000);
} else {
close();
errorAutoClose("Gagal memperbarui data perusahaan.");
}
} catch (err: any) {
2025-10-11 10:07:14 +00:00
close();
console.error("❌ Gagal update perusahaan:", err);
errorAutoClose(err?.message || "Terjadi kesalahan saat memperbarui data perusahaan.");
2025-10-11 10:07:14 +00:00
}
};
if (loadingData) {
return (
<Card className="p-6 w-full lg:w-2/3">
<div className="flex items-center justify-center py-8">
<div className="text-center">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mx-auto mb-4"></div>
<p>Memuat data perusahaan...</p>
</div>
</div>
</Card>
);
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Card className="p-6 w-full lg:w-2/3">
<CardHeader>
<CardTitle className="text-lg font-semibold">
Update Informasi Perusahaan
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{/* Logo Upload */}
<div className="space-y-2">
<Label>Logo Perusahaan</Label>
<div className="flex items-center gap-4">
<Input
type="file"
accept="image/*"
onChange={handleLogoChange}
className="max-w-xs"
/>
{previewLogo && (
<div className="flex items-center gap-2">
<div className="relative w-20 h-20 rounded-lg overflow-hidden border">
<Image
src={previewLogo}
alt="Company Logo"
fill
className="object-cover"
/>
</div>
{selectedLogoFile && (
<Button
type="button"
variant="outline"
size="sm"
onClick={handleRemoveLogo}
className="text-red-600 hover:text-red-700"
>
Remove
</Button>
)}
2025-10-11 10:07:14 +00:00
</div>
)}
</div>
<p className="text-sm text-gray-500">
Format yang didukung: JPG, PNG, WebP. Maksimal 5MB.
</p>
2025-10-11 10:07:14 +00:00
</div>
{/* Nama Perusahaan */}
<div>
<Label>Nama Perusahaan</Label>
<Controller
control={control}
name="companyName"
render={({ field }) => (
<Input {...field} placeholder="Masukkan nama perusahaan" />
)}
/>
{errors.companyName && (
<p className="text-red-500 text-sm">
{errors.companyName.message}
</p>
)}
</div>
{/* Alamat */}
<div>
<Label>Alamat</Label>
<Controller
control={control}
name="address"
render={({ field }) => (
<Textarea {...field} placeholder="Masukkan alamat lengkap" />
)}
/>
{errors.address && (
<p className="text-red-500 text-sm">{errors.address.message}</p>
)}
</div>
{/* Nomor Telepon */}
<div>
<Label>Nomor Telepon</Label>
<Controller
control={control}
name="phone"
render={({ field }) => (
<Input {...field} placeholder="Masukkan nomor telepon" />
)}
/>
{errors.phone && (
<p className="text-red-500 text-sm">{errors.phone.message}</p>
)}
</div>
{/* Website */}
<div>
<Label>Website Resmi</Label>
<Controller
control={control}
name="website"
render={({ field }) => (
<Input {...field} placeholder="https://example.com" />
)}
/>
{errors.website && (
<p className="text-red-500 text-sm">{errors.website.message}</p>
)}
</div>
{/* Deskripsi Perusahaan */}
<div>
<Label>Biodata / Deskripsi Perusahaan</Label>
<Controller
control={control}
name="description"
render={({ field }) => (
<Textarea
{...field}
placeholder="Ceritakan tentang perusahaan Anda..."
/>
)}
/>
</div>
{/* Status Aktif */}
{/* <div className="flex items-center space-x-2">
2025-10-11 10:07:14 +00:00
<Controller
control={control}
name="isActive"
render={({ field }) => (
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
)}
/>
<Label>Aktif</Label>
</div> */}
2025-10-11 10:07:14 +00:00
</CardContent>
<CardFooter className="flex justify-end gap-3">
<Button type="button" variant="outline" onClick={() => onCancel?.()}>
Cancel
</Button>
<Button
type="submit"
variant="outline"
className="flex items-center gap-2"
>
<SaveIcon className="h-4 w-4" />
Update
</Button>
2025-10-11 10:07:14 +00:00
</CardFooter>
</Card>
</form>
);
}