import { PlusOutlined } from '@ant-design/icons'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { App, AutoComplete, Button, Card, Form, Input, InputNumber, Select, Switch } from 'antd'
import { useEffect, useState } from 'react'

import {
  createAdminMockWorkOrder,
  fetchAdminMockCustomShops,
  fetchAdminWorkCategories,
} from '@/services/admin'
import { fetchAdminKuaishouIndustryShops } from '@/services/admin/kuaishou-industry'
import type { WorkOrderStatistics } from '@/types/worker-platform'
import { buildMockWorkOrderShopOptions } from '@/utils/mock-work-order'

import { formatMoney, formatStatus } from './shared'

const WORK_ORDER_STATISTICS_STATUS_ORDER = [
  'pending_material',
  'unassigned',
  'open',
  'in_progress',
  'pending_acceptance',
  'vip_evidence_pending',
  'problem',
  'accepted',
  'cancelled',
]

export function WorkOrderStatisticsBar({ statistics }: { statistics?: WorkOrderStatistics }) {
  if (!statistics) return null
  const profit = Number(statistics.userPaymentAmount || 0) - Number(statistics.rewardAmount || 0)
  const statusItems = WORK_ORDER_STATISTICS_STATUS_ORDER.map((status) => ({
    status,
    count: Number(statistics.statusCounts?.[status] || 0),
  }))
  const otherStatusItems = Object.entries(statistics.statusCounts || {})
    .filter(([status]) => !WORK_ORDER_STATISTICS_STATUS_ORDER.includes(status))
    .map(([status, count]) => ({ status, count: Number(count || 0) }))

  return (
    <Card size="small" bordered={false} className="worker-orders-statistics-card">
      <div className="worker-orders-statistics-summary">
        本次筛选统计共 <strong>{statistics.totalCount}</strong> 笔，预计总发单价{' '}
        <strong>{formatMoney(statistics.rewardAmount)}</strong>（不含销售提成），总接单价{' '}
        <strong>{formatMoney(statistics.userPaymentAmount)}</strong>，总退款{' '}
        <strong>{formatMoney(statistics.refundAmount)}</strong>，预计利润{' '}
        <strong className={profit < 0 ? 'is-negative' : ''}>{formatMoney(profit)}</strong>。
      </div>
      <div className="worker-orders-statistics-statuses">
        其中：
        {[...statusItems, ...otherStatusItems].map(({ status, count }, index) => (
          <span key={status}>
            {index > 0 ? '，' : ''}
            {formatStatus(status)}
            {count}笔
          </span>
        ))}
      </div>
    </Card>
  )
}

export function MockWorkOrderForm({ onCreated }: { onCreated: () => Promise<void> }) {
  const { message } = App.useApp()
  const queryClient = useQueryClient()
  const [loading, setLoading] = useState(false)
  const [form] = Form.useForm()
  const shopsQuery = useQuery({
    queryKey: ['admin-kuaishou-industry-shops', 'mock-work-order'],
    queryFn: fetchAdminKuaishouIndustryShops,
  })
  const customShopsQuery = useQuery({
    queryKey: ['admin-mock-custom-shops'],
    queryFn: fetchAdminMockCustomShops,
  })
  const categoriesQuery = useQuery({
    queryKey: ['admin-worker-platform-categories'],
    queryFn: fetchAdminWorkCategories,
  })
  const activeCategories = (categoriesQuery.data?.data.items || []).filter(
    (category) => category.status === 'active',
  )
  const defaultCategoryId = activeCategories[0]?.categoryId
  useEffect(() => {
    if (!form.getFieldValue('categoryId') && defaultCategoryId) {
      form.setFieldValue('categoryId', defaultCategoryId)
    }
  }, [defaultCategoryId, form])
  const shopOptions = [
    ...buildMockWorkOrderShopOptions(shopsQuery.data?.data.shops || []),
    ...(customShopsQuery.data?.data.items || []).map((name) => ({
      value: name,
      label: `${name}（自定义）`,
    })),
  ]

  async function submit(values: {
    platformOrderId: string
    sellerId: string
    productName: string
    categoryId?: number
    rewardAmount: number
    paymentAmount: number
    materialComplete?: boolean
    acceptanceMode?: string
  }) {
    setLoading(true)
    try {
      await createAdminMockWorkOrder({
        ...values,
        acceptanceMode: values.acceptanceMode || 'standard',
        categoryId: values.categoryId,
      })
      message.success('Mock 工单已生成')
      form.resetFields()
      if (defaultCategoryId) form.setFieldValue('categoryId', defaultCategoryId)
      // 自定义店铺由后端记忆，刷新后即可在下拉中选到。
      await queryClient.invalidateQueries({ queryKey: ['admin-mock-custom-shops'] })
      await onCreated()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '生成失败')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Form form={form} className="worker-order-mock-form" layout="inline" onFinish={submit}>
      <Form.Item
        className="worker-order-mock-field-order"
        label="订单号"
        name="platformOrderId"
        rules={[{ required: true, whitespace: true, message: '请填写订单号' }]}
      >
        <Input placeholder="请输入订单号" />
      </Form.Item>
      <Form.Item
        className="worker-order-mock-field-category"
        label="分类"
        name="categoryId"
        rules={[{ required: true, message: '请选择接单分类' }]}
      >
        <Select
          allowClear
          loading={categoriesQuery.isLoading}
          options={activeCategories.map((category) => ({
            value: category.categoryId,
            label: category.name,
          }))}
          placeholder="选择接单分类"
        />
      </Form.Item>
      <Form.Item
        className="worker-order-mock-field-shop"
        label="店铺"
        name="sellerId"
        rules={[{ required: true, whitespace: true, message: '请选择或输入店铺' }]}
      >
        <AutoComplete
          options={shopOptions}
          filterOption={(inputValue, option) =>
            String(option?.label ?? '')
              .toLowerCase()
              .includes(inputValue.toLowerCase()) ||
            String(option?.value ?? '')
              .toLowerCase()
              .includes(inputValue.toLowerCase())
          }
          placeholder={
            shopOptions.length > 0 ? '选择已配置店铺，或直接输入自定义店铺' : '输入自定义店铺'
          }
        />
      </Form.Item>
      <Form.Item
        className="worker-order-mock-field-product"
        label="商品"
        name="productName"
        rules={[{ required: true, whitespace: true, message: '请填写商品名称' }]}
      >
        <Input placeholder="请输入商品名称" />
      </Form.Item>
      <Form.Item
        className="worker-order-mock-field-amount"
        label="接单金额"
        name="rewardAmount"
        rules={[
          { required: true, message: '请填写接单金额' },
          { type: 'number', min: 0.01, message: '接单金额必须大于 0' },
        ]}
      >
        <InputNumber min={0.01} step={1} addonAfter="元" />
      </Form.Item>
      <Form.Item
        className="worker-order-mock-field-amount"
        label="用户付款金额"
        name="paymentAmount"
        rules={[
          { required: true, message: '请填写用户付款金额' },
          { type: 'number', min: 0.01, message: '用户付款金额必须大于 0' },
        ]}
      >
        <InputNumber min={0.01} step={1} addonAfter="元" />
      </Form.Item>
      <Form.Item
        className="worker-order-mock-field-complete"
        label="资料完整"
        name="materialComplete"
        valuePropName="checked"
      >
        <Switch />
      </Form.Item>
      <Form.Item
        className="worker-order-mock-field-complete"
        label="验收模式"
        name="acceptanceMode"
        initialValue="standard"
      >
        <Select
          style={{ width: 110 }}
          options={[
            { value: 'standard', label: '标准验收' },
            { value: 'friend_gift', label: '好友赠送' },
          ]}
        />
      </Form.Item>
      <Form.Item className="worker-order-mock-action">
        <Button type="primary" icon={<PlusOutlined />} htmlType="submit" loading={loading}>
          生成
        </Button>
      </Form.Item>
    </Form>
  )
}
