"use client"

import {
  getUserAll,
  getUserGroupAll,
  userGroupAdd,
} from "@/components/label/api/user"
import { useAllUserStore } from "@/components/label/store/auth"
import { Button, Group, Modal, Select, Stack, TextInput } from "@mantine/core"
import { useForm } from "@mantine/form"
import { notifications } from "@mantine/notifications"
import { useEffect, useMemo, useState } from "react"

interface ComponentProps {
  opened: boolean
  onCloseAction: (refresh?: boolean) => void
}

export default function CreateModal({ opened, onCloseAction }: ComponentProps) {
  const storeUserOpts = useAllUserStore((s) => s.userOpts)

  const [groupOpts, setGroupOpts] = useState<
    Array<{ label: string; value: string }>
  >([])
  const [userOpts, setUserOpts] = useState<
    Array<{ label: string; value: string }>
  >([])
  const [submitting, setSubmitting] = useState(false)

  const finalUserOpts = useMemo(() => {
    return userOpts.length > 0 ? userOpts : (storeUserOpts as any[])
  }, [storeUserOpts, userOpts])

  const form = useForm({
    initialValues: {
      group_name: "",
      leader_uid: "",
      parent_group_uuid: "",
    },
    validate: {
      group_name: (v) => (v.trim() ? null : "请输入用户组名称"),
      leader_uid: (v) => (v ? null : "请选择用户组负责人"),
    },
  })

  useEffect(() => {
    if (!opened) return
    const run = async () => {
      const [groupRes, userRes] = await Promise.all([
        getUserGroupAll(),
        getUserAll(),
      ])
      setGroupOpts(groupRes ?? [])
      setUserOpts(
        (userRes ?? []).map((u) => ({ label: u.label, value: String(u.value) }))
      )
    }
    queueMicrotask(run)
  }, [opened])

  const submit = form.onSubmit(async (values) => {
    try {
      setSubmitting(true)
      await userGroupAdd({
        group_name: values.group_name.trim(),
        leader_uid: Number(values.leader_uid),
        parent_group_uuid: values.parent_group_uuid,
      })
      notifications.show({
        color: "green",
        title: "操作成功",
        message: "已新增用户组",
      })
      form.reset()
      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("group_name")}
          />
          <Select
            label="用户组负责人"
            size="xs"
            radius="xs"
            withAsterisk
            searchable
            data={finalUserOpts.map((item) => {
              return {
                label: item.label.toString(),
                value: item.value.toString(),
              }
            })}
            {...form.getInputProps("leader_uid")}
          />
          <Select
            label="上级用户组"
            size="xs"
            radius="xs"
            searchable
            clearable
            data={groupOpts}
            {...form.getInputProps("parent_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>
  )
}
