import React, { useState, useEffect } from 'react';

const MemberForm = ({ member, onSubmit, onCancel }) => {
    const [formData, setFormData] = useState(member || {
        id_izkaznica: '',
        ime: '',
        priimek: '',
        spol: '',
        datum_rojstva: '',
        kraj_rojstva: '',
        drzavljanstvo: '',
        solska_izobrazba: '',
        telefondoma: '',
        telefonsluzba: '',
        telefonmobi: '',
        email: '',
        spletnastran: '',
        naslovbivalisca: '',
        ulica: '',
        postna_stevilka: '',
        posta: '',
        osnovni_poklic: '',
        sedanja_zaposlitev: '',
        prevajalska_praksa: '',
        nacin_pridobivanja_znanja_tujih_jezikov: '',
        datum_vclanitve: '',
        materni_jezik: '',
        objava_v_iskalniku: false
    });

    const handleChange = (e) => {
        const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
        setFormData({ ...formData, [e.target.name]: value });
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        onSubmit(formData);
    };

    return (
        <form onSubmit={handleSubmit}>
            <div>
                <label>
                    ID Izkaznica:
                    <input
                        type="number"
                        name="id_izkaznica"
                        value={formData.id_izkaznica}
                        onChange={handleChange}
                        required
                    />
                </label>
            </div>
            <div>
                <label>
                    Ime:
                    <input
                        type="text"
                        name="ime"
                        value={formData.ime}
                        onChange={handleChange}
                        required
                    />
                </label>
            </div>
            <div>
                <label>
                    Priimek:
                    <input
                        type="text"
                        name="priimek"
                        value={formData.priimek}
                        onChange={handleChange}
                        required
                    />
                </label>
            </div>
            <div>
                <label>
                    Spol:
                    <select name="spol" value={formData.spol} onChange={handleChange} required>
                        <option value="">Select...</option>
                        <option value="moski">Moški</option>
                        <option value="zenska">Ženski</option>
                    </select>
                </label>
            </div>
            <div>
                <label>
                    Datum rojstva:
                    <input
                        type="date"
                        name="datum_rojstva"
                        value={formData.datum_rojstva}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Kraj rojstva:
                    <input
                        type="text"
                        name="kraj_rojstva"
                        value={formData.kraj_rojstva}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Državljanstvo:
                    <input
                        type="text"
                        name="drzavljanstvo"
                        value={formData.drzavljanstvo}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Šolska izobrazba:
                    <input
                        type="text"
                        name="solska_izobrazba"
                        value={formData.solska_izobrazba}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Telefon (doma):
                    <input
                        type="tel"
                        name="telefondoma"
                        value={formData.telefondoma}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Telefon (služba):
                    <input
                        type="tel"
                        name="telefonsluzba"
                        value={formData.telefonsluzba}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Mobilni telefon:
                    <input
                        type="tel"
                        name="telefonmobi"
                        value={formData.telefonmobi}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Email:
                    <input
                        type="email"
                        name="email"
                        value={formData.email}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Spletna stran:
                    <input
                        type="url"
                        name="spletnastran"
                        value={formData.spletnastran}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Naslov bivališča:
                    <input
                        type="text"
                        name="naslovbivalisca"
                        value={formData.naslovbivalisca}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Ulica:
                    <input
                        type="text"
                        name="ulica"
                        value={formData.ulica}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Poštna številka:
                    <input
                        type="text"
                        name="postna_stevilka"
                        value={formData.postna_stevilka}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Pošta:
                    <input
                        type="text"
                        name="posta"
                        value={formData.posta}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Osnovni poklic:
                    <input
                        type="text"
                        name="osnovni_poklic"
                        value={formData.osnovni_poklic}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Sedanja zaposlitev:
                    <input
                        type="text"
                        name="sedanja_zaposlitev"
                        value={formData.sedanja_zaposlitev}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Prevajalska praksa:
                    <input
                        type="text"
                        name="prevajalska_praksa"
                        value={formData.prevajalska_praksa}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Način pridobivanja znanja tujih jezikov:
                    <input
                        type="text"
                        name="nacin_pridobivanja_znanja_tujih_jezikov"
                        value={formData.nacin_pridobivanja_znanja_tujih_jezikov}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Datum včlanitve:
                    <input
                        type="date"
                        name="datum_vclanitve"
                        value={formData.datum_vclanitve}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Materni jezik:
                    <input
                        type="text"
                        name="materni_jezik"
                        value={formData.materni_jezik}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <label>
                    Objava v iskalniku:
                    <input
                        type="checkbox"
                        name="objava_v_iskalniku"
                        checked={formData.objava_v_iskalniku}
                        onChange={handleChange}
                    />
                </label>
            </div>
            <div>
                <button type="submit">{member ? 'Update' : 'Add'} Member</button>
                <button type="button" onClick={onCancel}>Cancel</button>
            </div>
        </form>
    );
};

const MembersList = ({ members, onEdit, onDelete }) => {
    return (
        <div>
            <h2>Members List</h2>
            <table>
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Surname</th>
                    <th>Email</th>
                    <th>Actions</th>
                </tr>
                </thead>
                <tbody>
                {members.map(member => (
                    <tr key={member.id}>
                        <td>{member.id_izkaznica}</td>
                        <td>{member.ime}</td>
                        <td>{member.priimek}</td>
                        <td>{member.email}</td>
                        <td>
                            <button onClick={() => onEdit(member)}>Edit</button>
                            <button onClick={() => onDelete(member.id)}>Delete</button>
                        </td>
                    </tr>
                ))}
                </tbody>
            </table>
        </div>
    );
};

const App = () => {
    const [members, setMembers] = useState([]);
    const [editing, setEditing] = useState(null);
    const [showForm, setShowForm] = useState(false);

    const endpoint = `http://localhost:3000`;

    useEffect(() => {
        fetchMembers();
    }, []);

    const fetchMembers = async () => {
        try {
            const response = await fetch(`${endpoint}/express/api/v1/clan/`);
            const data = await response.json();
            setMembers(data);
        } catch (error) {
            console.error('Error fetching members:', error);
        }
    };

    const handleSubmit = async (formData) => {
        try {
            const url = editing
                ? `/express/api/v1/clan/${editing.id}`
                : '/express/api/v1/clan/';

            const response = await fetch(`${endpoint}${url}`, {
                method: editing ? 'PUT' : 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData),
            });

            if (response.ok) {
                fetchMembers();
                setEditing(null);
                setShowForm(false);
            } else {
                console.error('Error saving member');
            }
        } catch (error) {
            console.error('Error saving member:', error);
        }
    };

    const handleDelete = async (id) => {
        if (window.confirm('Are you sure you want to delete this member?')) {
            try {
                const response = await fetch(`${endpoint}/express/api/v1/clan/${id}`, {
                    method: 'DELETE',
                });
                console.log(response);

                if (response.ok) {
                    fetchMembers();
                } else {
                    console.error('Error deleting member');
                }
            } catch (error) {
                console.error('Error deleting member:', error);
            }
        }
    };

    const handleEdit = (member) => {
        setEditing(member);
        setShowForm(true);
    };

    const handleCancel = () => {
        setEditing(null);
        setShowForm(false);
    };

    return (
        <div>
            <h1>Člani</h1>
            <button onClick={() => setShowForm(true)}>Add New Member</button>

            {showForm ? (
                <div>
                    <h2>{editing ? 'Edit Member' : 'Add New Member'}</h2>
                    <MemberForm
                        member={editing}
                        onSubmit={handleSubmit}
                        onCancel={handleCancel}
                    />
                </div>
            ) : (
                <MembersList
                    members={members}
                    onEdit={handleEdit}
                    onDelete={handleDelete}
                />
            )}
        </div>
    );
};

export default App;