import {Input} from "@/components/Input/Input";
import React, {useState} from "react";
import Button from "@/components/Button/Button";
import {useModalContext} from "@/components/Modal/ModalContext";
import {add, update} from "@/api/customers";
import {useCustomerContext} from "@/api/context/Customer";

export default function Customer({ initialData }: any) {
    const { setContentModal } = useModalContext();
    const { fetchData } = useCustomerContext();

    const [formData, setFormData] = useState({
        id: initialData?.id || null,
        name: initialData?.name || "",
        phone: initialData?.phone || "",
        email: initialData?.email || "",
    });

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setFormData({
            ...formData,
            [name]: value
        });
    };

    const handleSubmit = async () => {
        if (formData.id === null) {
            await add(formData);
        } else {
            await update(formData);
        }
        fetchData();
        setContentModal(null);
    };

    return (
        <>
            <Input value={formData.name} onChange={handleChange} name="name">Фамилия Имя Отчество</Input>
            <Input value={formData.phone} onChange={handleChange} name="phone">Телефон</Input>
            <Input value={formData.email} onChange={handleChange} name="email">Почта</Input>
            <Button onClickAction={handleSubmit}>Сохранить</Button>
        </>
    );
}
