import {
  App,
  Button,
  Card,
  Checkbox,
  Form,
  Input,
  Popconfirm,
  Select,
  Space,
  Switch,
  Tag,
  Typography,
} from 'antd'
import { useEffect, useMemo, useState } from 'react'
import {
  CheckOutlined,
  DeleteOutlined,
  LinkOutlined,
  PlusOutlined,
  ShopOutlined,
} from '@ant-design/icons'

import { saveAdminWorkProductRuleMapping } from '@/services/admin'
import type { WorkProductRuleMapping } from '@/types/worker-platform'
import type { AdminKuaishouIndustryShopOption } from '@/types/admin'

type MappingFormValues = {
  mappingId?: number
  ruleId?: number
  sellerIds: string[]
  productScope: 'all_products' | 'selected_products'
  relItemId?: string
  itemTitle?: string
  relSkuId?: string
  skuNick?: string
  skuMatchMode: 'fuzzy' | 'exact'
  mappingType: 'product_default' | 'sku_exact' | 'sku_series'
  enabled?: boolean
}

export type SourcePrefill = {
  sellerId: string
  relItemId: string
  itemTitle: string
  relSkuId: string
  skuNick: string
}

export type WorkProductBindingFormProps = {
  ruleId: number
  ruleName?: string
  shops: AdminKuaishouIndustryShopOption[]
  mappings: WorkProductRuleMapping[]
  activeMappingId?: number | 'new' | null
  sourcePrefill?: SourcePrefill | null
  onSelectMapping: (mappingId: number | 'new') => void
  onDeleteMapping?: (mapping: WorkProductRuleMapping) => void
  onSaved: (savedMappingId?: number) => void
}

export function WorkProductBindingForm({
  ruleId,
  ruleName,
  shops,
  mappings,
  activeMappingId,
  sourcePrefill,
  onSelectMapping,
  onDeleteMapping,
  onSaved,
}: WorkProductBindingFormProps) {
  const { message } = App.useApp()
  const [form] = Form.useForm<MappingFormValues>()
  const [saving, setSaving] = useState(false)

  const shopNameBySellerId = useMemo(() => createShopNameBySellerId(shops), [shops])
  const sellerOptions = useMemo(() => {
    const knownSellerIds = shops.map((shop) => String(shop.sellerId || '').trim()).filter(Boolean)
    const prefillSellerIds = sourcePrefill
      ? [String(sourcePrefill.sellerId || '').trim()].filter(Boolean)
      : []
    const values = Array.from(new Set([...knownSellerIds, ...prefillSellerIds]))
      .sort((left, right) => left.localeCompare(right))
      .map((sellerId) => ({
        value: sellerId,
        label: formatShopLabel(sellerId, shopNameBySellerId),
      }))
    return values
  }, [shops, shopNameBySellerId, sourcePrefill])

  const currentMapping = useMemo(() => {
    if (activeMappingId === 'new') return null
    if (typeof activeMappingId === 'number') {
      return mappings.find((m) => m.mappingId === activeMappingId) || null
    }
    return mappings[0] || null
  }, [activeMappingId, mappings])

  const isNew = activeMappingId === 'new' || (!currentMapping && mappings.length === 0)

  useEffect(() => {
    if (currentMapping) {
      form.setFieldsValue({
        mappingId: currentMapping.mappingId,
        ruleId: currentMapping.ruleId,
        sellerIds: currentMapping.sellerIds,
        productScope:
          currentMapping.relItemId || currentMapping.itemTitle
            ? 'selected_products'
            : 'all_products',
        relItemId: currentMapping.relItemId,
        itemTitle: currentMapping.itemTitle,
        relSkuId: currentMapping.relSkuId,
        skuNick: currentMapping.skuNick,
        skuMatchMode: currentMapping.skuMatchMode,
        mappingType: currentMapping.mappingType,
        enabled: currentMapping.enabled,
      })
      return
    }
    form.resetFields()
    form.setFieldsValue({
      ruleId,
      mappingType: 'product_default',
      productScope: sourcePrefill?.relItemId ? 'selected_products' : 'all_products',
      skuMatchMode: 'fuzzy',
      enabled: true,
      sellerIds: sourcePrefill?.sellerId
        ? [sourcePrefill.sellerId].filter(Boolean)
        : sellerOptions.map((opt) => opt.value),
      relItemId: sourcePrefill?.relItemId || '',
      itemTitle: sourcePrefill?.itemTitle || '',
      relSkuId: sourcePrefill?.relSkuId || '',
      skuNick: sourcePrefill?.skuNick || '',
    })
  }, [currentMapping, form, isNew, ruleId, sellerOptions, sourcePrefill])

  function handleValuesChange(changedValues: Partial<MappingFormValues>) {
    if (changedValues.mappingType) {
      const isProductDefault = changedValues.mappingType === 'product_default'
      form.setFieldsValue({
        productScope: isProductDefault ? 'selected_products' : 'all_products',
        ...(isProductDefault ? {} : { relItemId: '', itemTitle: '' }),
      })
    }
    if (changedValues.productScope === 'all_products') {
      form.setFieldsValue({ relItemId: '', itemTitle: '' })
    }
    if (
      changedValues.sellerIds &&
      changedValues.sellerIds.length > 1 &&
      form.getFieldValue('mappingType') === 'product_default'
    ) {
      form.setFieldValue('relItemId', '')
    }
  }

  async function submit() {
    try {
      const values = await form.validateFields()
      const { productScope: _productScope, ...payload } = values
      const targetRuleId = ruleId || payload.ruleId
      if (!targetRuleId) {
        message.error('请选择接单模板')
        return
      }
      setSaving(true)
      const res = await saveAdminWorkProductRuleMapping({ ...payload, ruleId: targetRuleId })
      message.success(values.mappingId ? '商品绑定已更新' : '商品绑定已创建')
      onSaved(res.data?.mapping?.mappingId)
    } catch (error) {
      if (error && typeof error === 'object' && 'errorFields' in error) return
      message.error(error instanceof Error ? error.message : '保存商品绑定失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Card
      size="small"
      className="binding-editor-card"
      title={
        <div className="binding-editor-card-header">
          <Space size={8} wrap className="binding-pills-row">
            <LinkOutlined style={{ color: '#1677ff' }} />
            <Typography.Text strong style={{ fontSize: 13 }}>
              商品匹配规则:
            </Typography.Text>
            {mappings.map((m, index) => {
              const isSelected =
                !isNew &&
                (currentMapping?.mappingId === m.mappingId || (index === 0 && !currentMapping))
              const label =
                m.mappingType === 'product_default'
                  ? m.itemTitle || m.relItemId
                    ? '指定商品'
                    : '全部商品 (默认)'
                  : m.skuNick ||
                    m.relSkuId ||
                    (m.mappingType === 'sku_series' ? 'SKU数量系列' : 'SKU精确覆盖')
              return (
                <Tag.CheckableTag
                  key={m.mappingId}
                  checked={isSelected}
                  onChange={() => onSelectMapping(m.mappingId)}
                  className={`binding-pill-tag ${isSelected ? 'active' : ''}`}
                >
                  #{index + 1} {label}
                </Tag.CheckableTag>
              )
            })}
            <Button
              size="small"
              type={isNew ? 'primary' : 'dashed'}
              icon={<PlusOutlined />}
              onClick={() => onSelectMapping('new')}
              className="binding-add-btn"
            >
              添加新规则
            </Button>
          </Space>
        </div>
      }
      extra={
        <Space size={8}>
          {currentMapping && !isNew && onDeleteMapping ? (
            <Popconfirm
              title="确定删除此商品绑定规则？"
              description="删除后，快手订单将不再按此规则匹配到当前模板。"
              okText="删除"
              cancelText="取消"
              okButtonProps={{ danger: true }}
              onConfirm={() => onDeleteMapping(currentMapping)}
            >
              <Button size="small" type="text" danger icon={<DeleteOutlined />}>
                删除此规则
              </Button>
            </Popconfirm>
          ) : null}
          <Button
            type="primary"
            size="small"
            icon={<CheckOutlined />}
            loading={saving}
            onClick={submit}
          >
            {isNew ? '创建商品绑定' : '保存商品绑定'}
          </Button>
        </Space>
      }
    >
      <Form
        form={form}
        layout="vertical"
        onValuesChange={handleValuesChange}
        className="binding-form-content"
      >
        <Form.Item name="mappingId" hidden>
          <Input />
        </Form.Item>
        <Form.Item name="ruleId" hidden>
          <Input />
        </Form.Item>

        {/* 覆盖店铺 */}
        <Form.Item
          label={
            <Space size={4}>
              <ShopOutlined />
              <span>覆盖店铺</span>
            </Space>
          }
          name="sellerIds"
          rules={[{ required: true, message: '至少选择一个店铺' }]}
        >
          <ShopSelector options={sellerOptions} />
        </Form.Item>

        {/* 绑定类型 & 商品范围 & 状态 */}
        <div className="form-grid-3col">
          <Form.Item label="绑定类型" name="mappingType">
            <Select
              options={[
                { value: 'product_default', label: '商品默认模板' },
                { value: 'sku_series', label: 'SKU 数量系列' },
                { value: 'sku_exact', label: 'SKU 精确覆盖' },
              ]}
            />
          </Form.Item>

          <Form.Item noStyle shouldUpdate>
            {({ getFieldValue }) => {
              const mappingType = getFieldValue('mappingType')
              const isProductDefault = mappingType === 'product_default'
              return !isProductDefault ? (
                <Form.Item label="商品范围" name="productScope">
                  <Select
                    options={[
                      { value: 'all_products', label: '全部商品' },
                      { value: 'selected_products', label: '指定商品' },
                    ]}
                  />
                </Form.Item>
              ) : (
                <Form.Item label="快手大标题" name="itemTitle">
                  <Input placeholder="商品大标题或核心关键词" />
                </Form.Item>
              )
            }}
          </Form.Item>

          <Form.Item label="规则状态" name="enabled" valuePropName="checked">
            <Switch checkedChildren="已启用" unCheckedChildren="已停用" />
          </Form.Item>
        </div>

        {/* 商品ID / 大标题 / SKU 条件 */}
        <Form.Item noStyle shouldUpdate>
          {({ getFieldValue }) => {
            const mappingType = getFieldValue('mappingType')
            const isProductDefault = mappingType === 'product_default'
            const productScope = getFieldValue('productScope')
            const showProductScope = isProductDefault || productScope === 'selected_products'

            return (
              <div className="form-grid-3col">
                {showProductScope ? (
                  <Form.Item
                    label="关联商品 ID"
                    name="relItemId"
                    extra="支持多个商品ID，逗号/空格分隔"
                  >
                    <Input placeholder="如 123456789, 987654321" />
                  </Form.Item>
                ) : null}

                {!isProductDefault && showProductScope ? (
                  <Form.Item label="快手大标题" name="itemTitle" extra="可选，父商品分流">
                    <Input placeholder="可选，商品大标题关键字" />
                  </Form.Item>
                ) : null}

                {mappingType === 'sku_exact' ? (
                  <>
                    <Form.Item label="关联 SKU ID" name="relSkuId">
                      <Input placeholder="ext.relSkuId，0 自动忽略" />
                    </Form.Item>
                    <Form.Item label="具体 SKU 名称" name="skuNick">
                      <Input placeholder="ext.skuNick，完整精确匹配" />
                    </Form.Item>
                  </>
                ) : mappingType === 'sku_series' ? (
                  <>
                    <Form.Item label="SKU 系列名称" name="skuNick">
                      <Input placeholder="例如：指挥官密钥；自动覆盖 1个、10个等规格" />
                    </Form.Item>
                    <Form.Item label="SKU 匹配方式" name="skuMatchMode">
                      <Select
                        options={[
                          { value: 'fuzzy', label: '模糊匹配（兼容密钥/秘钥）' },
                          { value: 'exact', label: '精确匹配' },
                        ]}
                      />
                    </Form.Item>
                  </>
                ) : null}
              </div>
            )
          }}
        </Form.Item>
      </Form>
    </Card>
  )
}

function ShopSelector({
  value = [],
  onChange,
  options,
}: {
  value?: string[]
  onChange?: (nextValue: string[]) => void
  options: Array<{ value: string; label: string }>
}) {
  const optionValues = options.map((option) => option.value)
  const selectedValues = Array.isArray(value) ? value.map(String) : []
  const selectedOptionValues = selectedValues.filter((sellerId) => optionValues.includes(sellerId))
  const otherValues = selectedValues.filter((sellerId) => !optionValues.includes(sellerId))
  const allSelected = optionValues.length > 0 && selectedOptionValues.length === optionValues.length
  const partiallySelected = selectedOptionValues.length > 0 && !allSelected

  return (
    <div className="shop-selector-box-inline">
      <Checkbox
        checked={allSelected}
        disabled={optionValues.length === 0}
        indeterminate={partiallySelected}
        onChange={(event) =>
          onChange?.(event.target.checked ? [...otherValues, ...optionValues] : otherValues)
        }
        className="shop-all-toggle"
      >
        全选
      </Checkbox>
      <Checkbox.Group
        value={selectedValues}
        onChange={(nextValues) => onChange?.(nextValues.map(String))}
        className="shop-checkbox-inline-wrap"
      >
        {options.map((option) => (
          <Checkbox key={option.value} value={option.value} className="shop-chk-item">
            {option.label}
          </Checkbox>
        ))}
      </Checkbox.Group>
    </div>
  )
}

function createShopNameBySellerId(shops: AdminKuaishouIndustryShopOption[]) {
  const names = new Map<string, string>()
  for (const shop of shops) {
    const name = String(shop.shopName || '').trim()
    if (!name) continue
    const sellerId = String(shop.sellerId || '').trim()
    const shopId = String(shop.shopId || '').trim()
    if (sellerId) names.set(sellerId, name)
    if (shopId) names.set(shopId, name)
  }
  return names
}

function formatShopLabel(sellerId: string, shopNameBySellerId: Map<string, string>) {
  const name = shopNameBySellerId.get(sellerId)
  return name ? `${name}（${sellerId}）` : sellerId
}
