"use client"

import { userUpdateGroup } from "@/components/label/api/user"
import { User } from "@/components/label/api/user/typing"
import { Button, Group, Modal, Select, Stack, TextInput } from "@mantine/core"
import { useForm } from "@mantine/form"
import { notifications } from "@mantine/notifications"
import { useEffect, useState } from "react"

interface ComponentProps {
  opened: boolean
  data: User.UserInfo | null
  groupOpts: Array<{ label: string; value: string }>
  onCloseAction: (refresh?: boolean) => void
}

export default function EditUserModal({
  opened,
  data,
  groupOpts,
  onCloseAction,
}: ComponentProps) {
  const [submitting, setSubmitting] = useState(false)

  const form = useForm({
    initialValues: {
      name: "",
      group_uuid: "",
    },
    validate: {
      name: (v) => (v.trim() ? null : "请输入用户名"),
      group_uuid: (v) => (v ? null : "请选择组织"),
    },
  })

  useEffect(() => {
    if (!opened || !data) return
    form.setValues({
      name: data.name ?? "",
      group_uuid: data.group_uuid ?? "",
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [opened, data])

  const submit = form.onSubmit(async (values) => {
    if (!data?.uid) return
    try {
      setSubmitting(true)
      await userUpdateGroup({
        user_id: data.uid,
        group_uuid: values.group_uuid,
      })
      notifications.show({
        color: "green",
        title: "操作成功",
        message: "已更新用户信息",
      })
      onCloseAction(true)
    } catch (e) {
      notifications.show({
        color: "red",
        title: "操作失败",
        message: e instanceof Error ? e.message : "请求失败",
      })
    } finally {
      setSubmitting(false)
    }
  })

  return (
    <Modal
      opened={opened}
      onClose={() => onCloseAction()}
      title="编辑用户"
      centered
      size={560}
      closeOnClickOutside={false}>
      <form onSubmit={submit}>
        <Stack gap="sm">
          <TextInput
            label="用户名"
            size="xs"
            radius="xs"
            withAsterisk
            {...form.getInputProps("name")}
          />
          <Select
            label="组织"
            size="xs"
            radius="xs"
            withAsterisk
            searchable
            data={groupOpts}
            {...form.getInputProps("group_uuid")}
          />
          <Group justify="flex-end" mt="xs">
            <Button
              variant="default"
              size="xs"
              radius="xs"
              onClick={() => onCloseAction()}>
              取消
            </Button>
            <Button type="submit" size="xs" radius="xs" loading={submitting}>
              确定
            </Button>
          </Group>
        </Stack>
      </form>
    </Modal>
  )
}
