import type { Route } from "./+types/users.create";
import PageTitle from "~/components/ui/PageTitle";
import useRoutes from "~/hooks/useRoutes";
import { useNavigate } from "react-router";
import { useState } from "react";
import Alert from "~/components/ui/Alert";
import { createUser } from "~/utils/api/usersApi";
import { Link } from "react-router";
import SolidButton from "~/components/ui/Buttons/SolidButton";

export function meta({}: Route.MetaArgs) {
  return [
    { title: "Dish Planner - Create User" },
    { name: "description", content: "Create a new user" },
  ];
}

const CreateUsersPage = () => {
  const [name, setName] = useState<string>("");
  const [error, setError] = useState<string>("");
  const navigate = useNavigate();
  const routes = useRoutes();

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

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

    createUser(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="py-2 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"
          autoFocus={true}
          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">
          Create
        </SolidButton>
      </form>
    </div>
  );
};

export default CreateUsersPage;
