"use client"; import React, { useState } from "react"; import { Card, CardHeader, CardContent } from "@/components/ui/Card"; import Button from "@/components/ui/Button"; import { Input } from "@/components/ui/Input"; export default function ContactForm({ initialData = null, onSave, onCancel }) { const [form, setForm] = useState({ name: "", phones: [""], email: "", company: "", position: "", contact_type: "other", notes: "", is_active: true, ...initialData, }); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); // Handle initial data with phones React.useEffect(() => { if (initialData) { let phones = [""]; if (initialData.phone) { try { // Try to parse as JSON array first const parsed = JSON.parse(initialData.phone); phones = Array.isArray(parsed) ? parsed : [initialData.phone]; } catch { // Fall back to comma-separated string phones = initialData.phone.split(',').map(p => p.trim()).filter(p => p); } } setForm(prev => ({ ...prev, ...initialData, phones: phones.length > 0 ? phones : [""] })); } }, [initialData]); const isEdit = !!initialData; function handleChange(e) { const { name, value, type, checked } = e.target; setForm((prev) => ({ ...prev, [name]: type === "checkbox" ? checked : value, })); } function handlePhoneChange(index, value) { setForm(prev => ({ ...prev, phones: prev.phones.map((phone, i) => i === index ? value : phone) })); } function addPhone() { setForm(prev => ({ ...prev, phones: [...prev.phones, ""] })); } function removePhone(index) { if (form.phones.length > 1) { setForm(prev => ({ ...prev, phones: prev.phones.filter((_, i) => i !== index) })); } } async function handleSubmit(e) { e.preventDefault(); setLoading(true); setError(null); try { // Filter out empty phones and prepare data const filteredPhones = form.phones.filter(phone => phone.trim()); const submitData = { ...form, phone: filteredPhones.length > 1 ? JSON.stringify(filteredPhones) : (filteredPhones[0] || null), phones: undefined // Remove phones array from submission }; const url = isEdit ? `/api/contacts/${initialData.contact_id}` : "/api/contacts"; const method = isEdit ? "PUT" : "POST"; const response = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(submitData), }); if (!response.ok) { const data = await response.json(); throw new Error(data.error || "Failed to save contact"); } const contact = await response.json(); onSave?.(contact); } catch (err) { setError(err.message); } finally { setLoading(false); } } return (

{isEdit ? "Edytuj kontakt" : "Nowy kontakt"}

{error && (
{error}
)} {/* Basic Information */}
{form.phones.map((phone, index) => (
handlePhoneChange(index, e.target.value)} placeholder={index === 0 ? "+48 123 456 789" : "Dodatkowy numer"} className="flex-1" /> {form.phones.length > 1 && ( )}
))}