import { SearchOutlined } from '@ant-design/icons'
import { App, Button, Card, Form, Input, Radio, Result, Space, Typography } from 'antd'
import { useState } from 'react'

import ImageUpload from '@/components/files/ImageUpload'
import { lookupCollectOrder, submitCollectOrder } from '@/services/worker'
import type { CollectLookupOrder, UploadedFile } from '@/types/worker-platform'

export default function CollectPage() {
  const { message } = App.useApp()
  const [orderNo, setOrderNo] = useState('')
  const [lookupOrders, setLookupOrders] = useState<CollectLookupOrder[]>([])
  const [lookupLoading, setLookupLoading] = useState(false)
  const [submittingWorkOrderId, setSubmittingWorkOrderId] = useState(0)
  const [screenshotsByOrder, setScreenshotsByOrder] = useState<Record<number, UploadedFile[]>>({})
  const [complete, setComplete] = useState(false)

  async function submitLookup(values: { orderNo: string }) {
    setLookupLoading(true)
    setComplete(false)
    try {
      const nextOrderNo = String(values.orderNo || '').trim()
      setOrderNo(nextOrderNo)
      await refreshLookupOrders(nextOrderNo)
    } catch (error) {
      setLookupOrders([])
      message.error(error instanceof Error ? error.message : '查询失败')
    } finally {
      setLookupLoading(false)
    }
  }

  async function submitMaterial(order: CollectLookupOrder, values: Record<string, string>) {
    setSubmittingWorkOrderId(order.workOrderId)
    try {
      const response = await submitCollectOrder({
        orderNo,
        workOrderId: order.workOrderId,
        fields: values,
        screenshots: screenshotsByOrder[order.workOrderId] || [],
      })
      message.success(response.data.complete ? '当前商品资料已完善' : '当前商品资料已提交')
      await refreshLookupOrders(orderNo, { allowCompleteWhenNotFound: true })
    } catch (error) {
      message.error(error instanceof Error ? error.message : '提交失败')
    } finally {
      setSubmittingWorkOrderId(0)
    }
  }

  return (
    <main className="collect-page">
      <Card className="collect-card" bordered={false}>
        <Typography.Title level={3}>订单资料补充</Typography.Title>
        <Typography.Paragraph type="secondary">
          请填写正确订单号，匹配成功后继续补充资料。
        </Typography.Paragraph>

        <Form layout="vertical" onFinish={submitLookup}>
          <Space.Compact className="full-width">
            <Form.Item
              name="orderNo"
              className="collect-order-input"
              rules={[{ required: true, message: '请输入订单号' }]}
            >
              <Input placeholder="订单号" />
            </Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              icon={<SearchOutlined />}
              loading={lookupLoading}
            >
              查询
            </Button>
          </Space.Compact>
        </Form>

        {complete ? (
          <Result
            status="success"
            title="资料已提交完成"
            subTitle="订单已进入待分配状态，请等待处理。"
          />
        ) : null}

        {!complete && lookupOrders.length > 1 ? (
          <Typography.Paragraph type="secondary" className="platform-section-gap">
            当前订单有 {lookupOrders.length} 个待完善商品，请逐个提交资料。
          </Typography.Paragraph>
        ) : null}

        {lookupOrders.map((currentOrder) => (
          <Card
            key={currentOrder.workOrderId}
            className="platform-section-gap"
            title={currentOrder.productName}
            extra={<Typography.Text type="secondary">{currentOrder.workOrderNo}</Typography.Text>}
            size="small"
          >
            <Typography.Paragraph type="secondary">
              订单号：{currentOrder.platformOrderId}
            </Typography.Paragraph>
            <Form
              key={currentOrder.workOrderId}
              layout="vertical"
              initialValues={currentOrder.values || {}}
              onFinish={(values) => submitMaterial(currentOrder, values)}
            >
              {currentOrder.fields.map((field) => (
                <Form.Item
                  key={field.key}
                  label={field.label}
                  name={field.key}
                  rules={
                    field.required ? [{ required: true, message: `请选择/填写${field.label}` }] : []
                  }
                >
                  {field.type === 'select' && (field.options || []).length > 0 ? (
                    <Radio.Group
                      options={(field.options || []).map((option) => ({
                        label: option,
                        value: option,
                      }))}
                    />
                  ) : (
                    <Input />
                  )}
                </Form.Item>
              ))}
              <Form.Item label="买家主页截图">
                <ImageUpload
                  scene="collect-material"
                  scope="collect"
                  maxCount={5}
                  showPasteHint
                  captureGlobalPaste
                  value={
                    screenshotsByOrder[currentOrder.workOrderId] ?? currentOrder.screenshots ?? []
                  }
                  onChange={(files) =>
                    setScreenshotsByOrder((prev) => ({
                      ...prev,
                      [currentOrder.workOrderId]: files,
                    }))
                  }
                />
              </Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={submittingWorkOrderId === currentOrder.workOrderId}
              >
                提交资料
              </Button>
            </Form>
          </Card>
        ))}
      </Card>
    </main>
  )

  async function refreshLookupOrders(
    currentOrderNo: string,
    options: { allowCompleteWhenNotFound?: boolean } = {},
  ) {
    try {
      const response = await lookupCollectOrder(currentOrderNo)
      setLookupOrders(response.data.orders || [])
      setComplete(false)
    } catch (error) {
      if (options.allowCompleteWhenNotFound && isCollectOrderNotFoundError(error)) {
        setLookupOrders([])
        setComplete(true)
        return
      }
      throw error
    }
  }
}

function isCollectOrderNotFoundError(error: unknown) {
  return (
    String((error as { errorCode?: string })?.errorCode || '').trim() === 'collect_order_not_found'
  )
}
