"use client"

import { Button, Group, Modal, MultiSelect, Stack } from "@mantine/core"
import { useForm } from "@mantine/form"
import { useEffect } from "react"

export default function AdminUserModal(props: {
  opened: boolean
  value: number[]
  options: Array<{ label: string; value: string }>
  onCloseAction: (next?: number[]) => void
}) {
  const { opened, value, options, onCloseAction } = props

  const form = useForm({
    initialValues: { users: value.map(String) },
  })

  useEffect(() => {
    if (!opened) return
    form.setValues({ users: value.map(String) })
    form.resetDirty()
  }, [opened, value, form])

  return (
    <Modal
      opened={opened}
      onClose={() => onCloseAction()}
      title="编辑项目管理员"
      centered
      size={560}>
      <form
        onSubmit={form.onSubmit((values) => {
          const next = values.users
            .map((v) => Number(v))
            .filter((v) => Number.isFinite(v))
          onCloseAction(next)
        })}>
        <Stack gap="sm">
          <MultiSelect
            label="项目管理员"
            data={options}
            searchable
            clearable
            value={form.values.users}
            onChange={(v) => form.setFieldValue("users", v)}
          />
          <Group justify="flex-end" gap="sm">
            <Button variant="default" onClick={() => onCloseAction()}>
              取消
            </Button>
            <Button type="submit">保存</Button>
          </Group>
        </Stack>
      </form>
    </Modal>
  )
}
