"use client";

import type { Lobby } from "@/server/db/schema";
import React from "react";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { lobbyPatchSchema } from "@/lib/validations/lobby";
import { toast } from "sonner";
import { api } from "@/trpc/react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { appRoutes } from "@/config/app.routes";
import { Slider } from "@/components/ui/slider";
import { getMinMax } from "@/lib/validations/utils";

function LobbyForm({
  server_lobby,
  cb,
}: {
  server_lobby?: Lobby;
  cb?: () => void;
}) {
  const [loading, setLoading] = React.useState(false);
  const { mutateAsync: createLobby } = api.lobby.create.useMutation();
  const { mutateAsync: updateLobby } = api.lobby.update.useMutation();
  const router = useRouter();
  const form = useForm<z.infer<typeof lobbyPatchSchema>>({
    resolver: zodResolver(lobbyPatchSchema),
    defaultValues: {
      name: server_lobby?.name ?? "Random Name",
      maxPlayers: server_lobby?.maxPlayers ?? 2,
    },
  });
  async function onSubmit(lobby: z.infer<typeof lobbyPatchSchema>) {
    setLoading(true);
    const existingLobby = Boolean(server_lobby?.id?.length);
    const result = existingLobby
      ? await updateLobby({ lobby, lobbyId: server_lobby?.id! })
      : await createLobby({ lobby });
    cb?.();
    if (result) {
      if (!existingLobby) {
        router.push(appRoutes.currentlobby);
        router.refresh();
      }
    } else toast.error("Something went wrong.");
    setLoading(false);
    form.reset();
  }

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="w-full space-y-8">
        <FormField
          control={form.control}
          name="name"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Name</FormLabel>
              <FormControl>
                <Input
                  className="placeholder:text-white/50"
                  placeholder="What is you lobbies name?"
                  {...field}
                />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="maxPlayers"
          render={({ field }) => {
            const { min, max } = getMinMax(lobbyPatchSchema.shape.maxPlayers);
            return (
              <FormItem>
                <FormLabel>
                  Max Players
                  <span className="text-xl font-bold">{`${field.value}`}</span>
                </FormLabel>
                <FormControl>
                  <Slider
                    className="w-full max-w-xs"
                    defaultValue={[field.value]}
                    max={max ?? 100}
                    min={min ?? 1}
                    step={1}
                    onValueChange={(value) => field.onChange(value[0])}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            );
          }}
        />
        <div className="flex items-center justify-end">
          <Button
            type="submit"
            disabled={
              loading ||
              (Boolean(server_lobby?.id?.length) && !form.formState.isDirty)
            }
            className="ml-auto"
          >
            {server_lobby?.id?.length ? "Update" : "Create"} Lobby
          </Button>
        </div>
      </form>
    </Form>
  );
}

export default LobbyForm;
