import React, {FC, useState} from "react";
import {useRouter} from "next/navigation";
import useRoutes from "@/hooks/useRoutes";
import {updateUser} from "@/utils/api/usersApi";
import PageTitle from "@/components/ui/PageTitle";
import Link from "next/link";
import Alert from "@/components/ui/Alert";
import {UserType} from "@/types/UserType";
import SolidButton from "@/components/ui/Buttons/SolidButton";

interface Props {
    user: UserType;
}

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

    const [name, setName] = useState<string>(user.name);
    const [error, setError] = useState<string>('');
    const router = useRouter();
    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(() => {
                router.push(routes.user.index())
            })
    }

    return (
        <div className="w-full flex flex-col items-center">
            <PageTitle>Create User</PageTitle>
            <Link href={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;