import { updatePlayer } from "@/features/players/server";
import { Stack, TextInput } from "@mantine/core";
import { useForm } from "@mantine/form";
import { Trans, useLingui } from "@lingui/react/macro";
import { Player } from "../../types";
import Button from "@/components/button";
import { useOptimisticMutation } from "@/lib/tanstack-query/hooks";
import { playerKeys } from "../../queries";

interface NameUpdateFormProps {
  player: Player;
  toggle: () => void;
}

const NameUpdateForm = ({ player, toggle }: NameUpdateFormProps) => {
  const { t } = useLingui();

  const form = useForm({
    initialValues: {
      first_name: player.first_name,
      last_name: player.last_name,
    },
    validate: {
      first_name: (value: string | undefined) => {
        if (!value || value.length === 0) return t`First name is required`;
        if (!/^[a-zA-Z\s]{2,20}$/.test(value))
          return t`First name must be 2-20 characters long and contain only letters`;
      },
      last_name: (value: string | undefined) => {
        if (!value || value.length === 0) return t`Last name is required`;
        if (!/^[a-zA-Z\s]{2,20}$/.test(value))
          return t`Last name must be 2-20 characters long and contain only letters`;
      },
    },
  });

  const { mutate: updateName, isPending } = useOptimisticMutation({
    mutationFn: async (data: { first_name: string; last_name: string }) =>
      await updatePlayer({ data }),
    onSuccess: toggle,
    onError: toggle,
    successMessage: t`Name updated successfully!`,
    optimisticUpdate: (oldData, variables) => {
      if (!oldData) return oldData;
      return {
        ...oldData,
        first_name: variables.first_name,
        last_name: variables.last_name,
      };
    },
    queryKey: playerKeys.details(player.id)
  });

  const handleSubmit = async (data: {
    first_name: string | undefined;
    last_name: string | undefined;
  }) => {
    if (!data.first_name || !data.last_name) return;
    await updateName({
      first_name: data.first_name,
      last_name: data.last_name,
    });
  };
  return (
    <form onSubmit={form.onSubmit(handleSubmit)}>
      <Stack gap="xs">
        <TextInput label={t`First Name`} {...form.getInputProps("first_name")} />
        <TextInput label={t`Last Name`} {...form.getInputProps("last_name")} />
        <Button loading={isPending} type="submit">
          <Trans>Save</Trans>
        </Button>
        <Button variant="subtle" color="red" onClick={toggle}>
          <Trans>Cancel</Trans>
        </Button>
      </Stack>
    </form>
  );
};

export default NameUpdateForm;
