import React, {useState} from "react";
import { useNavigate } from "react-router";
import useRoutes from "~/hooks/useRoutes";
import {updateUser} from "~/utils/api/usersApi";
import PageTitle from "~/components/ui/PageTitle";
import { Link } from "react-router";
import Alert from "~/components/ui/Alert";
import {UserType} from "~/types/UserType";
import SolidButton from "~/components/ui/Buttons/SolidButton";

interface Props {
    user: UserType;
}

const EditUserForm = ({ user }: Props) => {

    const [name, setName] = useState<string>(user.name);
    const [error, setError] = useState<string>('');
    const navigate = useNavigate();
    const routes = useRoutes();

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();

        // validateName
        if (!name.trim()) {
            setError('Name cannot be empty.');
            return;
        }

        updateUser(user, name)
            .then(() => {
                navigate(routes.user.index())
            })
    }

    return (
        <div className="w-full flex flex-col items-center">
            <PageTitle>Create User</PageTitle>
            <Link to={routes.user.index()} className="mr-auto">Back to users</Link>

            <form onSubmit={handleSubmit} className="w-full max-w-sm mt-4 border-secondary border-2 rounded p-4">
                {
                    error != '' && <Alert type="error" className="mt-4">{ error }</Alert>
                }

                <label htmlFor="name">Name</label>
                <input type="text"
                       placeholder=""
                       name="name"
                       id="name"
                       value={name}
                       onChange={(e) => setName(e.target.value)}
                       className="w-full p-2 border rounded bg-primary border-secondary bg-gray-600 text-secondary"
                />

                <SolidButton type="submit" className="mt-4">Update</SolidButton>
            </form>
        </div>
    );
}

export default EditUserForm;