"use client"

import { projectReview } from "@/components/label/api/project"
import { usePermissionStore } from "@/components/label/store/auth"
import {
  Button,
  Group,
  Modal,
  NumberInput,
  Radio,
  Stack,
  Text,
  TextInput,
  Textarea,
} from "@mantine/core"
import { useForm } from "@mantine/form"
import { notifications } from "@mantine/notifications"
import { useEffect, useMemo } from "react"

export default function ReviewModal(props: {
  opened: boolean
  record: any
  onCloseAction: (refresh?: boolean) => void
}) {
  const { opened, record, onCloseAction } = props
  const userName = usePermissionStore((s) => s.user_name)

  const form = useForm({
    initialValues: {
      test_proportion: undefined as number | undefined,
      pass: true,
      review_comment: "",
    },
  })

  useEffect(() => {
    if (!opened) return
    form.setValues({
      test_proportion:
        record && typeof record.test_proportion === "number"
          ? record.test_proportion
          : null,
      pass: true,
      review_comment: "",
    })
    form.resetDirty()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [opened, record])

  const showEditableTestProportion = useMemo(() => {
    return record?.status === 1
  }, [record?.status])

  const showReadonlyTestProportion = useMemo(() => {
    return record?.status === 101 || record?.status === 102
  }, [record?.status])

  const fullLabel = useMemo(() => {
    if (!record) return "-"
    const name = record.label_schema_name ?? ""
    const version = record.label_schema_version ?? ""
    if (!name) return record.full_label ?? "-"
    return version ? `${name} - ${version}` : name
  }, [record])

  return (
    <Modal
      opened={opened}
      onClose={() => onCloseAction()}
      title="审核项目"
      centered
      closeOnClickOutside={false}
      size={640}>
      <form
        onSubmit={form.onSubmit(async (values) => {
          if (!record?.id) return
          try {
            const params: any = {
              project_id: record.id,
              project_name: record.name,
              pass: values.pass,
              review_comment: values.review_comment || undefined,
              review_user: userName ?? "",
            }
            if (showEditableTestProportion) {
              if (typeof values.test_proportion !== "number") {
                notifications.show({
                  color: "red",
                  title: "校验失败",
                  message: "请填写抽取比例",
                })
                return
              }
              params.test_proportion = values.test_proportion
            } else if (showReadonlyTestProportion) {
              if (typeof record.test_proportion === "number") {
                params.test_proportion = record.test_proportion
              }
            }

            await projectReview(params)
            notifications.show({
              color: "green",
              title: "操作成功",
              message: "已提交审核",
            })
            onCloseAction(true)
          } catch (e) {
            notifications.show({
              color: "red",
              title: "操作失败",
              message: e instanceof Error ? e.message : "请求失败",
            })
          }
        })}>
        <Stack gap="sm">
          <TextInput
            label="项目名称"
            size="xs"
            radius="xs"
            value={record?.name ?? "-"}
            readOnly
          />
          <TextInput
            label="项目负责人"
            size="xs"
            radius="xs"
            value={record?.create_user ?? record?.owner ?? "-"}
            readOnly
          />
          <TextInput
            label="数据量"
            size="xs"
            radius="xs"
            value={
              record?.data_size || record?.data_size === 0
                ? String(record.data_size)
                : "-"
            }
            readOnly
          />
          <TextInput
            label="标注数据源"
            size="xs"
            radius="xs"
            value={record?.data_source ?? "-"}
            readOnly
          />
          <TextInput label="标注方案" value={fullLabel} readOnly />

          {showEditableTestProportion ? (
            <NumberInput
              label="抽取比例"
              size="xs"
              radius="xs"
              min={0}
              max={100}
              step={1}
              hideControls
              rightSection={
                <Text size="xs" c="dimmed" style={{ paddingRight: 8 }}>
                  %
                </Text>
              }
              value={form.values.test_proportion}
              onChange={(v) =>
                form.setFieldValue(
                  "test_proportion",
                  typeof v === "number" ? v : undefined
                )
              }
            />
          ) : null}

          {showReadonlyTestProportion ? (
            <TextInput
              label="抽取比例"
              size="xs"
              radius="xs"
              value={
                typeof record?.test_proportion === "number"
                  ? `${record.test_proportion}%`
                  : "-"
              }
              readOnly
            />
          ) : null}

          <Radio.Group
            label="是否通过"
            size="xs"
            value={form.values.pass ? "true" : "false"}
            onChange={(v) => form.setFieldValue("pass", v === "true")}>
            <Group gap="md" mt={6}>
              <Radio value="true" label="通过" size="xs" />
              <Radio value="false" label="不通过" size="xs" />
            </Group>
          </Radio.Group>

          <Textarea
            label="审核意见"
            size="xs"
            radius="xs"
            minRows={3}
            autosize
            placeholder="请输入"
            value={form.values.review_comment}
            onChange={(e) =>
              form.setFieldValue("review_comment", e.currentTarget.value)
            }
          />

          <Group justify="flex-end" gap="sm" mt="xs">
            <Button
              variant="default"
              size="xs"
              radius="xs"
              onClick={() => onCloseAction()}>
              取消
            </Button>
            <Button type="submit" size="xs" radius="xs">
              确定
            </Button>
          </Group>
        </Stack>
      </form>
    </Modal>
  )
}
