import { useEffect, useMemo, useState } from "react"
import { EditOutlined, EyeInvisibleOutlined, EyeOutlined, StopOutlined } from "@ant-design/icons"
import { Alert, Button, Col, Form, Input, Modal, Row, Select } from "antd"
import { toast } from "../../utils/toast"
import {
  createProduct,
  type Product,
  type ProductStatus,
  type ProductType,
} from "../api/product"
import type { ProductGroup } from "../api/product_catalog"

interface Props {
  open: boolean
  onClose: () => void
  onCreated: (product: Product) => void
  groups: ProductGroup[]
  defaultGroupId?: number | null
}

interface FormValues {
  group_id: number
  type: ProductType
  status: ProductStatus
  sku: string
  name: string
}

const TYPE_OPTIONS: { value: ProductType; label: string }[] = [
  { value: "server", label: "云服务器" },
  { value: "hosting", label: "虚拟主机" },
  { value: "domain", label: "域名" },
  { value: "ssl", label: "SSL 证书" },
  { value: "license", label: "软件授权" },
  { value: "other", label: "其他" },
]

const STATUS_OPTIONS: { value: ProductStatus; label: React.ReactNode }[] = [
  { value: "draft", label: <span><EditOutlined /> 草稿</span> },
  { value: "active", label: <span><EyeOutlined /> 在售</span> },
  { value: "hidden", label: <span><EyeInvisibleOutlined /> 隐藏</span> },
  { value: "deprecated", label: <span><StopOutlined /> 停售</span> },
]

export default function ProductQuickCreateModal({
  open,
  onClose,
  onCreated,
  groups,
  defaultGroupId,
}: Props) {
  const [form] = Form.useForm<FormValues>()
  const [saving, setSaving] = useState(false)

  const groupOptions = useMemo(
    () => groups.map((group) => ({ value: group.id, label: group.name })),
    [groups],
  )

  useEffect(() => {
    if (!open) return
    form.setFieldsValue({
      group_id: defaultGroupId ?? groups[0]?.id,
      type: "server",
      status: "draft",
      sku: "",
      name: "",
    })
  }, [defaultGroupId, form, groups, open])

  const submit = async () => {
    const values = await form.validateFields()
    setSaving(true)
    try {
      const res = await createProduct({
        group_id: values.group_id,
        sku: values.sku.trim(),
        name: values.name.trim(),
        type: values.type,
        status: values.status,
        pricings: [],
      })
      if (res.data) {
        toast.success("已创建，正在跳转到详情页")
        onCreated(res.data)
      }
    } catch (e: unknown) {
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "创建失败")
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      destroyOnHidden
      width={560}
      title="添加产品"
      onCancel={onClose}
      footer={[
        <Button key="cancel" onClick={onClose} disabled={saving}>取消</Button>,
        <Button key="submit" type="primary" loading={saving} onClick={submit}>
          创建并继续
        </Button>,
      ]}
    >
      <Alert
        type="info"
        showIcon
        title="先创建草稿产品"
        description="下一步进入详情页配置规格、价格周期、系统列表和上游开通参数。"
        style={{ marginBottom: 18 }}
      />

      <Form
        form={form}
        layout="vertical"
        requiredMark="optional"
        initialValues={{ type: "server", status: "draft" }}
      >
        <Form.Item
          label="所属产品组"
          name="group_id"
          rules={[{ required: true, message: "请选择产品组" }]}
        >
          <Select
            showSearch
            optionFilterProp="label"
            options={groupOptions}
            placeholder={groupOptions.length === 0 ? "请先创建产品组" : "请选择产品组"}
          />
        </Form.Item>

        <Row gutter={12}>
          <Col span={12}>
            <Form.Item label="形态" name="type" rules={[{ required: true, message: "请选择产品形态" }]}>
              <Select options={TYPE_OPTIONS} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="初始上架状态" name="status" rules={[{ required: true, message: "请选择状态" }]}>
              <Select options={STATUS_OPTIONS} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={12}>
          <Col span={12}>
            <Form.Item
              label="SKU"
              name="sku"
              rules={[{ required: true, whitespace: true, message: "请填写 SKU" }]}
            >
              <Input placeholder="server-hk-cn2-1c1g" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label="名称"
              name="name"
              rules={[{ required: true, whitespace: true, message: "请填写产品名称" }]}
            >
              <Input placeholder="香港 CN2 · 1H1G 入门" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  )
}
