import { Group, Box, Button, TextInput, Stack, Textarea } from "@mantine/core";
import React, { useState } from "react";
import { useCreateGroupMutation } from "@/features/group/queries/group-query.ts";
import { useForm } from "@mantine/form";
import { z } from "zod/v4";
import { useNavigate } from "react-router-dom";
import { MultiUserSelect } from "@/features/group/components/multi-user-select.tsx";
import { useTranslation } from "react-i18next";
import { zod4Resolver } from 'mantine-form-zod-resolver';

type FormValues = {
  name: string;
  description: string;
};

export function CreateGroupForm() {
  const { t } = useTranslation();
  const createGroupMutation = useCreateGroupMutation();
  const [userIds, setUserIds] = useState<string[]>([]);
  const navigate = useNavigate();

  // Build the schema with friendly, translated validation messages (issue #130)
  const formSchema = z.object({
    name: z
      .string()
      .trim()
      .min(2, t("Group name must be at least 2 characters"))
      .max(100, t("Group name must be 100 characters or fewer")),
    description: z
      .string()
      .max(500, t("Description must be 500 characters or fewer")),
  });

  const form = useForm<FormValues>({
    validate: zod4Resolver(formSchema),
    initialValues: {
      name: "",
      description: "",
    },
  });

  const handleMultiSelectChange = (value: string[]) => {
    setUserIds(value);
  };

  const handleSubmit = async (data: {
    name?: string;
    description?: string;
  }) => {
    const groupData = {
      name: data.name,
      description: data.description,
      userIds: userIds,
    };

    const createdGroup = await createGroupMutation.mutateAsync(groupData);
    navigate(`/settings/groups/${createdGroup.id}`);
  };

  return (
    <>
      <Box maw="500" mx="auto">
        <form onSubmit={form.onSubmit((values) => handleSubmit(values))}>
          <Stack>
            <TextInput
              withAsterisk
              id="name"
              label={t("Group name")}
              placeholder={t("e.g Developers")}
              variant="filled"
              data-autofocus
              {...form.getInputProps("name")}
            />

            <Textarea
              id="description"
              label={t("Group description")}
              placeholder={t("e.g Group for developers")}
              variant="filled"
              autosize
              minRows={2}
              maxRows={8}
              {...form.getInputProps("description")}
            />

            <MultiUserSelect
              label={t("Add group members")}
              onChange={handleMultiSelectChange}
            />
          </Stack>

          <Group justify="flex-end" mt="md">
            <Button type="submit">{t("Create")}</Button>
          </Group>
        </form>
      </Box>
    </>
  );
}
