import { useEffect } from "react"
import { DeleteOutlined, EyeInvisibleOutlined, EyeOutlined, FolderOpenOutlined } from "@ant-design/icons"
import { Button, Form, Input, InputNumber, Modal, Select, Space, Switch, Typography } from "antd"
import { toast } from "../../utils/toast"
import { ICON_CATALOG } from "./iconsCatalog"
import {
  createCategory,
  deleteCategory,
  updateCategory,
  type ProductCategory,
} from "../api/product_catalog"

interface Props {
  open: boolean
  onClose: () => void
  onSaved: () => void
  initial?: ProductCategory | null
}

interface CategoryFormValues {
  slug: string
  name: string
  description?: string
  icon?: string
  sort_order?: number
  status: "active" | "hidden"
  is_featured?: boolean
  featured_label?: string
}

const { Text } = Typography

const iconOptions = ICON_CATALOG.map((item) => ({
  value: item.name,
  label: `${item.label} · ${item.name}`,
}))

export default function ProductCategoryFormModal({ open, onClose, onSaved, initial }: Props) {
  const [form] = Form.useForm<CategoryFormValues>()
  const isFeatured = Form.useWatch("is_featured", form)
  const isEdit = !!initial

  useEffect(() => {
    if (!open) return
    form.setFieldsValue({
      slug: initial?.slug ?? "",
      name: initial?.name ?? "",
      description: initial?.description ?? "",
      icon: initial?.icon ?? undefined,
      sort_order: initial?.sort_order ?? 0,
      status: initial?.status ?? "active",
      is_featured: initial?.is_featured ?? false,
      featured_label: initial?.featured_label ?? "推荐",
    })
  }, [form, initial, open])

  const submit = async () => {
    try {
      const values = await form.validateFields()
      const payload = {
        name: values.name.trim(),
        description: values.description?.trim() || null,
        icon: values.icon || null,
        sort_order: values.sort_order ?? 0,
        status: values.status,
        is_featured: !!values.is_featured,
        featured_label: values.featured_label?.trim() || "推荐",
      }

      if (isEdit && initial) {
        await updateCategory(initial.id, { ...payload, slug: initial.slug })
        toast.success("已保存")
      } else {
        await createCategory({ ...payload, slug: values.slug.trim() })
        toast.success("已添加")
      }
      onSaved()
      onClose()
    } catch (e: unknown) {
      if ((e as { errorFields?: unknown[] })?.errorFields) return
      const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
      toast.error(detail || "保存失败")
    }
  }

  const remove = () => {
    if (!initial) return
    Modal.confirm({
      title: `删除分类「${initial.name}」？`,
      content: "删除后不可恢复，且已有产品组的分类可能无法删除。",
      okText: "删除",
      okButtonProps: { danger: true },
      cancelText: "取消",
      async onOk() {
        try {
          await deleteCategory(initial.id)
          toast.success("已删除")
          onSaved()
          onClose()
        } catch (e: unknown) {
          const detail = (e as { response?: { data?: { detail?: string } } })?.response?.data?.detail
          toast.error(detail || "删除失败")
        }
      },
    })
  }

  return (
    <Modal
      open={open}
      title={
        <Space>
          <FolderOpenOutlined />
          {isEdit ? "编辑分类" : "添加产品分类"}
        </Space>
      }
      width={560}
      destroyOnHidden
      onCancel={onClose}
      onOk={submit}
      okText={isEdit ? "保存" : "添加"}
      cancelText="取消"
      footer={(_, { OkBtn, CancelBtn }) => (
        <Space style={{ width: "100%", justifyContent: "space-between" }}>
          {isEdit ? (
            <Button danger type="text" icon={<DeleteOutlined />} onClick={remove}>
              删除
            </Button>
          ) : (
            <Text type="secondary" style={{ fontSize: 12 }}>分类会展示在前台产品入口</Text>
          )}
          <Space>
            <CancelBtn />
            <OkBtn />
          </Space>
        </Space>
      )}
    >
      <Form form={form} layout="vertical" requiredMark="optional">
        <Form.Item
          label="slug"
          name="slug"
          rules={[{ required: !isEdit, message: "请填写 slug" }]}
        >
          <Input disabled={isEdit} placeholder="cloud-server" />
        </Form.Item>

        <Form.Item label="名称" name="name" rules={[{ required: true, message: "请填写名称" }]}>
          <Input placeholder="云服务器" />
        </Form.Item>

        <Form.Item label="描述" name="description">
          <Input.TextArea rows={3} placeholder="用于后台备注或后续展示扩展" />
        </Form.Item>

        <Space align="start" size={16} style={{ width: "100%" }}>
          <Form.Item label="图标" name="icon" style={{ flex: 1 }}>
            <Select
              allowClear
              showSearch
              placeholder="选择图标"
              options={iconOptions}
              optionFilterProp="label"
            />
          </Form.Item>
          <Form.Item label="排序" name="sort_order" style={{ width: 120 }}>
            <InputNumber min={0} precision={0} style={{ width: "100%" }} />
          </Form.Item>
          <Form.Item label="状态" name="status" style={{ width: 150 }}>
            <Select
              options={[
                { value: "active", label: <Space><EyeOutlined />展示</Space> },
                { value: "hidden", label: <Space><EyeInvisibleOutlined />隐藏</Space> },
              ]}
            />
          </Form.Item>
        </Space>

        <Space align="start" size={16} style={{ width: "100%" }}>
          <Form.Item label="首页推荐" name="is_featured" valuePropName="checked">
            <Switch
              checkedChildren="推荐"
              unCheckedChildren="普通"
              onChange={(checked) => {
                if (checked && !form.getFieldValue("featured_label")) {
                  form.setFieldsValue({ featured_label: "推荐" })
                }
              }}
            />
          </Form.Item>

          {isFeatured && (
            <Form.Item
              label="自定义显示文字"
              name="featured_label"
              rules={[{ max: 24, message: "最多 24 个字符" }]}
              style={{ flex: 1 }}
            >
              <Input placeholder="推荐" />
            </Form.Item>
          )}
        </Space>
      </Form>
    </Modal>
  )
}
