import {
  CheckOutlined,
  FormOutlined,
  PlusOutlined,
  ReloadOutlined,
  SendOutlined,
  SyncOutlined,
  TeamOutlined,
  WarningOutlined,
} from '@ant-design/icons'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {
  App,
  Button,
  Card,
  Descriptions,
  Drawer,
  Form,
  Input,
  InputNumber,
  Modal,
  Select,
  Space,
  Statistic,
  Switch,
  Table,
  Tabs,
  Tag,
  Typography,
} from 'antd'
import type { TableColumnsType } from 'antd'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router'

import JsonPreview from '@/components/admin/JsonPreview'
import ImageUpload from '@/components/files/ImageUpload'
import ImagePreviewList from '@/components/files/ImagePreviewList'
import PageHeader from '@/components/admin/PageHeader'
import {
  acceptAdminWorkOrder,
  createAdminMockWorkOrder,
  creditAdminWorkerWallet,
  deleteAdminWorkCategory,
  deleteAdminWorkerLevel,
  fetchAdminWorkerFinanceConfig,
  fetchAdminWorkerFinanceRequests,
  fetchAdminWorkCategories,
  fetchAdminWorkOrderSharing,
  fetchAdminWorkProductRules,
  fetchAdminWorkerLevels,
  fetchAdminWorkerPlatformSummary,
  fetchAdminWorkerUsers,
  fetchAdminWorkOrders,
  markAdminWorkOrderProblem,
  publishAdminWorkOrder,
  reviewAdminWorkerFinanceRequest,
  resolveAdminProblemWorkOrder,
  reviewAdminWorkerUser,
  saveAdminWorkerFinanceConfig,
  saveAdminWorkCategory,
  saveAdminWorkProductRule,
  saveAdminWorkerLevel,
  submitAdminWorkOrderMaterial,
  syncAdminWorkerOrdersFromSource,
  unpublishAdminWorkOrder,
  updateAdminWorkOrderSharing,
} from '@/services/admin'
import type {
  CollectField,
  UploadedFile,
  WorkCategory,
  WorkOrder,
  WorkOrderShare,
  WorkProductRule,
  WorkerFinanceConfig,
  WorkerFinanceRequest,
  WorkerLevel,
  WorkerUser,
} from '@/types/worker-platform'
import {
  ADMIN_DEFAULT_PAGE_SIZE,
  buildAdminTablePagination,
} from '@/utils/admin-pagination'
import { formatAdminDateTime } from '@/utils/admin-time'
import { formatMoney } from './shared'

export default function ProductRulesPanel() {
  const { message } = App.useApp()
  const queryClient = useQueryClient()
  const [form] = Form.useForm()
  const rulesQuery = useQuery({
    queryKey: ['admin-worker-platform-product-rules'],
    queryFn: () => fetchAdminWorkProductRules(),
  })
  const categoriesQuery = useQuery({
    queryKey: ['admin-worker-platform-categories'],
    queryFn: () => fetchAdminWorkCategories(),
  })

  async function saveRule(values: {
    ruleKey: string
    provider?: string
    platform?: string
    shopId?: string
    skuCode?: string
    productName?: string
    matchType?: string
    categoryId?: number
    rewardAmount?: number
    requiredDepositAmount?: number
    depositThresholdAmount?: number
    sharingEnabled?: boolean
    sharingTotalQuantity?: number
    sharingUnitReward?: number
    sharingTotalAmount?: number
    timeoutMinutes?: number
    timeoutPolicy?: string
    fieldsText?: string
    enabled?: boolean
    autoCreate?: boolean
  }) {
    try {
      await saveAdminWorkProductRule(values)
      message.success('物品规则已保存')
      form.resetFields()
      await Promise.all([
        queryClient.invalidateQueries({
          queryKey: ['admin-worker-platform-product-rules'],
        }),
        queryClient.invalidateQueries({
          queryKey: ['admin-worker-platform-summary'],
        }),
      ])
    } catch (error) {
      message.error(error instanceof Error ? error.message : '保存失败')
    }
  }

  function syncSharingRuleForm(next: {
    sharingTotalQuantity?: number
    sharingUnitReward?: number
    sharingTotalAmount?: number
  }) {
    const values = form.getFieldsValue()
    const unitReward = Number(next.sharingUnitReward ?? values.sharingUnitReward ?? 0)
    const totalQuantity = Number(
      next.sharingTotalQuantity ?? values.sharingTotalQuantity ?? 1,
    )
    const totalAmount = Number(next.sharingTotalAmount ?? values.sharingTotalAmount ?? 0)
    if (next.sharingTotalAmount !== undefined) {
      const quantity = unitReward > 0 ? Math.max(1, Math.round(totalAmount / unitReward)) : 1
      form.setFieldsValue({
        sharingTotalQuantity: quantity,
        sharingTotalAmount: quantity * unitReward,
      })
      return
    }
    form.setFieldsValue({
      sharingTotalAmount: unitReward * totalQuantity,
    })
  }

  const columns: TableColumnsType<WorkProductRule> = [
    {
      title: '规则',
      minWidth: 260,
      render: (_, row) => (
        <div className="cell-stack">
          <Typography.Text strong>
            {row.productName || row.skuCode}
          </Typography.Text>
          <Typography.Text type="secondary">{row.ruleKey}</Typography.Text>
        </div>
      ),
    },
    {
      title: '店铺',
      width: 120,
      render: (_, row) => {
        const shopId = String(row.shopId || '')
        return shopId ? (
          <Tag color="geekblue">{shopId}</Tag>
        ) : (
          <Tag>通配</Tag>
        )
      },
    },
    {
      title: 'SKU',
      dataIndex: 'skuCode',
      width: 180,
      render: (value) => String(value || '-'),
    },
    { title: '分类', width: 140, render: (_, row) => row.categoryName || '-' },
    {
      title: '接单金额',
      width: 120,
      render: (_, row) => formatMoney(row.rewardAmount),
    },
    {
      title: '押金',
      width: 120,
      render: (_, row) => formatMoney(row.requiredDepositAmount),
    },
    {
      title: '匹配',
      width: 130,
      render: (_, row) => (row.matchType === 'exact' ? '精确' : '包含'),
    },
    {
      title: '状态',
      width: 150,
      render: (_, row) => (
        <Space>
          <Tag color={row.enabled ? 'green' : 'default'}>
            {row.enabled ? '启用' : '停用'}
          </Tag>
          {row.autoCreate ? <Tag color="blue">自动创建</Tag> : null}
          {row.sharing?.enabled ? (
            <Tag color="purple">
              拼单 {formatMoney(row.sharing.unitReward)}/份
            </Tag>
          ) : null}
        </Space>
      ),
    },
  ]

  return (
    <section className="platform-panel-stack">
      <Card title="保存物品规则" bordered={false}>
        <Form
          form={form}
          layout="vertical"
          className="worker-rule-form"
          initialValues={{
            platform: 'kuaishou',
            matchType: 'contains',
            rewardAmount: 25,
            depositThresholdAmount: 200,
            enabled: true,
            autoCreate: false,
            sharingEnabled: false,
            sharingTotalQuantity: 10,
            sharingUnitReward: 5,
            sharingTotalAmount: 50,
            fieldsText:
              'gameId:游戏编号\ngameNickname:游戏昵称\nsystem:系统#安卓,苹果\nserverZone:区服#QQ区,微信区',
          }}
          onFinish={saveRule}
        >
          <div className="worker-rule-grid">
            <Form.Item
              label="规则标识"
              name="ruleKey"
              rules={[{ required: true, message: '请输入规则标识' }]}
            >
              <Input placeholder="skin-training" />
            </Form.Item>
            <Form.Item label="来源" name="provider">
              <Input placeholder="留空通配，如 91kaquan" />
            </Form.Item>
            <Form.Item label="平台" name="platform">
              <Input placeholder="kuaishou" />
            </Form.Item>
            <Form.Item label="店铺" name="shopId">
              <Input placeholder="留空通配" />
            </Form.Item>
            <Form.Item label="SKU" name="skuCode">
              <Input placeholder="优先精确匹配" />
            </Form.Item>
            <Form.Item label="商品名" name="productName">
              <Input placeholder="用于包含/精确匹配" />
            </Form.Item>
            <Form.Item label="匹配方式" name="matchType">
              <Select
                options={[
                  { value: 'contains', label: '包含' },
                  { value: 'exact', label: '精确' },
                ]}
              />
            </Form.Item>
            <Form.Item label="分类" name="categoryId">
              <Select
                allowClear
                loading={categoriesQuery.isLoading}
                options={(categoriesQuery.data?.data.items || []).map(
                  (item) => ({
                    value: item.categoryId,
                    label: item.name,
                  }),
                )}
              />
            </Form.Item>
            <Form.Item label="接单金额" name="rewardAmount">
              <InputNumber
                min={0.01}
                step={1}
                addonAfter="元"
                className="full-width"
              />
            </Form.Item>
            <Form.Item label="押金阈值" name="depositThresholdAmount">
              <InputNumber
                min={0}
                step={10}
                addonAfter="元"
                className="full-width"
              />
            </Form.Item>
            <Form.Item label="固定押金" name="requiredDepositAmount">
              <InputNumber
                min={0}
                step={10}
                addonAfter="元"
                className="full-width"
              />
            </Form.Item>
            <Form.Item label="排序" name="sortOrder">
              <InputNumber min={0} max={9999} className="full-width" />
            </Form.Item>
            <Form.Item label="启用" name="enabled" valuePropName="checked">
              <Switch />
            </Form.Item>
            <Form.Item
              label="自动创建"
              name="autoCreate"
              valuePropName="checked"
            >
              <Switch />
            </Form.Item>
            <Form.Item
              label="启用拼单"
              name="sharingEnabled"
              valuePropName="checked"
              tooltip="开启后按下方总数量与单价生成拼单工单"
            >
              <Switch />
            </Form.Item>
          </div>
          <Form.Item noStyle shouldUpdate>
            {({ getFieldValue }) =>
              getFieldValue('sharingEnabled') ? (
                <Space size={16} wrap style={{ marginBottom: 16 }}>
                  <Form.Item
                    label="拼单总数量"
                    name="sharingTotalQuantity"
                    rules={[{ required: true, message: '请填写总数量' }]}
                  >
                    <InputNumber
                      min={1}
                      max={100000}
                      addonAfter="份"
                      onChange={(value) =>
                        syncSharingRuleForm({
                          sharingTotalQuantity: Number(value) || 0,
                        })
                      }
                    />
                  </Form.Item>
                  <Form.Item
                    label="拼单单价"
                    name="sharingUnitReward"
                    rules={[{ required: true, message: '请填写单价' }]}
                    tooltip="每个数量份对应的报酬，修改后总价自动重算"
                  >
                    <InputNumber
                      min={0.01}
                      step={1}
                      addonAfter="元"
                      onChange={(value) =>
                        syncSharingRuleForm({
                          sharingUnitReward: Number(value) || 0,
                        })
                      }
                    />
                  </Form.Item>
                  <Form.Item
                    label="拼单总价"
                    name="sharingTotalAmount"
                    rules={[{ required: true, message: '请填写总价' }]}
                    tooltip="总价 = 单价 × 数量，修改总价会自动反推数量"
                  >
                    <InputNumber
                      min={0.01}
                      step={1}
                      addonAfter="元"
                      onChange={(value) =>
                        syncSharingRuleForm({
                          sharingTotalAmount: Number(value) || 0,
                        })
                      }
                    />
                  </Form.Item>
                </Space>
              ) : null
            }
          </Form.Item>
          <Form.Item
            label="资料字段"
            name="fieldsText"
            extra="每行一个字段：key:名称，下拉项用 # 分隔（如 system:系统#安卓,苹果）"
          >
            <Input.TextArea rows={4} />
          </Form.Item>
          <Form.Item
            label="默认任务时限"
            name="timeoutMinutes"
            tooltip="自动创建的工单继承该时限，打手抢单后开始计时；0 表示不限时"
          >
            <InputNumber min={0} step={5} addonAfter="分钟" />
          </Form.Item>
          <Form.Item
            label="默认超时策略"
            name="timeoutPolicy"
            tooltip="reopen：释放押金退回大厅；cancel_release：取消退押金；cancel_deduct：取消扣押金"
          >
            <Select
              style={{ width: 260 }}
              options={[
                { value: 'reopen', label: '释放押金退回大厅' },
                { value: 'cancel_release', label: '取消订单并退还押金' },
                { value: 'cancel_deduct', label: '取消订单并扣除押金' },
              ]}
            />
          </Form.Item>
          <Button type="primary" htmlType="submit">
            保存规则
          </Button>
        </Form>
      </Card>
      <Card
        title="物品规则"
        extra={
          <Button
            icon={<ReloadOutlined />}
            loading={rulesQuery.isFetching}
            onClick={() => rulesQuery.refetch()}
          >
            刷新
          </Button>
        }
        bordered={false}
      >
        <Table<WorkProductRule>
          rowKey="ruleId"
          loading={rulesQuery.isLoading}
          dataSource={rulesQuery.data?.data.items || []}
          columns={columns}
          pagination={false}
          scroll={{ x: 1200 }}
        />
      </Card>
    </section>
  )
}

