import { PictureOutlined } from '@ant-design/icons'
import { Button, Form, Input, Modal, Radio, Space, Tag, Typography } from 'antd'
import type { FormInstance } from 'antd'

import ImageUpload from '@/components/files/ImageUpload'
import type {
  UploadedFile,
  WorkerCancelRequestRisk,
  WorkerOrderFeedback,
  WorkOrder,
} from '@/types/worker-platform'

import {
  canAutoAcceptOrder,
  canSubmitAcceptance,
  canSupplementAcceptedEvidence,
  getDisplayOrderNo,
  hasSubmittedAcceptance,
} from './worker-order-utils'

export type AcceptanceFormValues = { note?: string }
export type WorkerNoteFormValues = { note?: string }
export type CancelRequestFormValues = { reason?: string }
export type FeedbackFormValues = { content?: string }
export type GiftMaterialFormValues = {
  gameNickname: string
  gameId: string
  serverZone: string
  system?: string
  note?: string
}

type NoteTheme = 'success' | 'processing' | 'danger' | 'warning' | 'purple' | 'default'

const PRESET_NOTE_TAGS: Array<{ label: string; theme: NoteTheme }> = [
  { label: '已安排', theme: 'success' },
  { label: '打单中', theme: 'processing' },
  { label: '账号问题', theme: 'danger' },
  { label: '排队中', theme: 'purple' },
  { label: '未安排', theme: 'warning' },
  { label: '暂缓做单', theme: 'warning' },
]

export function WorkerOrderModals({
  isMobile,
  feedbackOrder,
  feedbacks,
  feedbackForm,
  onCloseFeedback,
  onSubmitFeedback,
  cancelRequestOrder,
  cancelRequestRisk,
  cancelRequestForm,
  onCloseCancelRequest,
  onSubmitCancelRequest,
  noteOrder,
  noteForm,
  onCloseNote,
  onSaveNote,
  editingOrder,
  acceptanceFiles,
  acceptanceForm,
  workerCanAutoAcceptWithoutEvidence,
  onCloseAcceptance,
  onAcceptanceFilesChange,
  onSubmitAcceptance,
  onSaveAcceptanceImages,
  giftMaterialOrder,
  giftMaterialForm,
  giftMaterialFiles,
  onCloseGiftMaterial,
  onGiftMaterialFilesChange,
  onSubmitGiftMaterial,
}: {
  isMobile: boolean
  feedbackOrder: WorkOrder | null
  feedbacks: WorkerOrderFeedback[]
  feedbackForm: FormInstance<FeedbackFormValues>
  onCloseFeedback: () => void
  onSubmitFeedback: (values: FeedbackFormValues) => void | Promise<void>
  cancelRequestOrder: WorkOrder | null
  cancelRequestRisk: WorkerCancelRequestRisk | undefined
  cancelRequestForm: FormInstance<CancelRequestFormValues>
  onCloseCancelRequest: () => void
  onSubmitCancelRequest: (values: CancelRequestFormValues) => void | Promise<void>
  noteOrder: WorkOrder | null
  noteForm: FormInstance<WorkerNoteFormValues>
  onCloseNote: () => void
  onSaveNote: (values: WorkerNoteFormValues) => void | Promise<void>
  editingOrder: WorkOrder | null
  acceptanceFiles: UploadedFile[]
  acceptanceForm: FormInstance<AcceptanceFormValues>
  workerCanAutoAcceptWithoutEvidence: boolean
  onCloseAcceptance: () => void
  onAcceptanceFilesChange: (files: UploadedFile[]) => void
  onSubmitAcceptance: (values: AcceptanceFormValues) => void | Promise<void>
  onSaveAcceptanceImages: (values: AcceptanceFormValues) => void | Promise<void>
  giftMaterialOrder: WorkOrder | null
  giftMaterialForm: FormInstance<GiftMaterialFormValues>
  giftMaterialFiles: UploadedFile[]
  onCloseGiftMaterial: () => void
  onGiftMaterialFilesChange: (files: UploadedFile[]) => void
  onSubmitGiftMaterial: (values: GiftMaterialFormValues) => void | Promise<void>
}) {
  const feedbackItems = feedbacks.filter((item) => item.workOrderId === feedbackOrder?.workOrderId)
  return (
    <>
      <Modal
        title={`问题反馈 · ${getDisplayOrderNo(feedbackOrder)}`}
        open={Boolean(feedbackOrder)}
        width={isMobile ? '92%' : 540}
        onCancel={onCloseFeedback}
        onOk={() => feedbackForm.submit()}
        okText="提交反馈"
        destroyOnHidden
      >
        <Typography.Paragraph type="secondary">
          可反馈客户资料错误、账号异常或无法继续处理等问题。客服处理后会在反馈记录中回复。
        </Typography.Paragraph>
        <Form form={feedbackForm} layout="vertical" onFinish={onSubmitFeedback}>
          <Form.Item
            label="问题说明"
            name="content"
            rules={[{ required: true, whitespace: true, message: '请填写问题说明' }]}
          >
            <Input.TextArea
              rows={5}
              maxLength={500}
              showCount
              placeholder="例如：客户提供的游戏账号密码错误，无法登录"
            />
          </Form.Item>
        </Form>
        {feedbackItems.length > 0 ? (
          <Space direction="vertical" size={6} style={{ width: '100%' }}>
            <Typography.Text type="secondary">该订单最近反馈</Typography.Text>
            {feedbackItems.slice(0, 3).map((item) => (
              <Typography.Text key={item.feedbackId} type="secondary">
                {item.status === 'resolved' ? '已处理' : '待处理'}：{item.content}
                {item.reply ? `；客服回复：${item.reply}` : ''}
              </Typography.Text>
            ))}
          </Space>
        ) : null}
      </Modal>

      <Modal
        title={`申请取消 · ${getDisplayOrderNo(cancelRequestOrder)}`}
        open={Boolean(cancelRequestOrder)}
        width={isMobile ? '92%' : 520}
        onCancel={onCloseCancelRequest}
        onOk={() => cancelRequestForm.submit()}
        okText="提交申请"
        destroyOnHidden
      >
        <Space direction="vertical" size={8} style={{ width: '100%', marginBottom: 16 }}>
          <Typography.Text type="secondary">
            提交后由客服审核；通过后退还本次冻结押金，订单或拼单份额将回到大厅。
          </Typography.Text>
          <Typography.Text type="secondary">
            今日申请：{cancelRequestRisk?.dailyUsed || 0}/{cancelRequestRisk?.dailyLimit || 5}
            ；累计通过：
            {cancelRequestRisk?.approvedTotal || 0} 次。
          </Typography.Text>
          <Typography.Text type="warning">
            每累计 10 次通过申请最多降一级；VIP1 期间累计 5 次通过将封禁账号。
          </Typography.Text>
        </Space>
        <Form form={cancelRequestForm} layout="vertical" onFinish={onSubmitCancelRequest}>
          <Form.Item
            label="申请原因"
            name="reason"
            rules={[{ required: true, whitespace: true, message: '请填写申请取消原因' }]}
          >
            <Input.TextArea
              rows={4}
              maxLength={300}
              showCount
              placeholder="请说明无法继续处理的原因"
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={`订单备注 · ${getDisplayOrderNo(noteOrder)}`}
        open={Boolean(noteOrder)}
        width={isMobile ? '92%' : 460}
        onCancel={onCloseNote}
        onOk={() => noteForm.submit()}
        destroyOnHidden
      >
        <Form form={noteForm} layout="vertical" onFinish={onSaveNote}>
          <Form.Item label="快捷选择标签" style={{ marginBottom: 12 }}>
            <div className="worker-note-preset-tags">
              {PRESET_NOTE_TAGS.map((item) => (
                <Tag
                  key={item.label}
                  className={`worker-note-preset-tag theme-${item.theme}`}
                  onClick={() => noteForm.setFieldsValue({ note: item.label })}
                >
                  {item.label}
                </Tag>
              ))}
            </div>
          </Form.Item>
          <Form.Item label="备注内容" name="note">
            <Input.TextArea
              rows={3}
              maxLength={100}
              showCount
              placeholder="请输入备注说明（如：已联系买家、账号异常中等）"
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={
          editingOrder &&
          (canSupplementAcceptedEvidence(editingOrder) || hasSubmittedAcceptance(editingOrder))
            ? '补充验收图片'
            : '验收图片'
        }
        open={Boolean(editingOrder)}
        width={isMobile ? '96%' : 620}
        onCancel={onCloseAcceptance}
        destroyOnHidden
        footer={
          editingOrder ? (
            <Space>
              <Button onClick={onCloseAcceptance}>取消</Button>
              {canSupplementAcceptedEvidence(editingOrder) ? (
                <Button type="primary" onClick={() => acceptanceForm.submit()}>
                  补充图片
                </Button>
              ) : (
                <>
                  <Button
                    onClick={() => void onSaveAcceptanceImages(acceptanceForm.getFieldsValue())}
                  >
                    {hasSubmittedAcceptance(editingOrder) ? '保存修改' : '保存暂存'}
                  </Button>
                  {canSubmitAcceptance(editingOrder) ? (
                    <Button type="primary" onClick={() => acceptanceForm.submit()}>
                      提交验收
                    </Button>
                  ) : null}
                </>
              )}
            </Space>
          ) : null
        }
      >
        <Form form={acceptanceForm} layout="vertical" onFinish={onSubmitAcceptance}>
          {!editingOrder || !canSupplementAcceptedEvidence(editingOrder) ? (
            <Form.Item label="完成说明" name="note">
              <Input.TextArea rows={3} placeholder="可补充代练结果、注意事项或截图说明。" />
            </Form.Item>
          ) : null}
          <Form.Item
            label="验收图片"
            required={
              !editingOrder ||
              canSupplementAcceptedEvidence(editingOrder) ||
              !canAutoAcceptOrder(editingOrder, workerCanAutoAcceptWithoutEvidence)
            }
            extra={
              editingOrder && canSupplementAcceptedEvidence(editingOrder)
                ? '仅可追加新图片，原有验收图片会保留。'
                : editingOrder &&
                    canAutoAcceptOrder(editingOrder, workerCanAutoAcceptWithoutEvidence)
                  ? 'VIP 免审核可先提交，验收后需在 24 小时内补充图片。'
                  : undefined
            }
          >
            <ImageUpload
              scene="worker-acceptance"
              scope="worker"
              value={acceptanceFiles}
              onChange={onAcceptanceFilesChange}
              maxCount={20}
              showPasteHint
            />
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title={`好友赠送资料 · ${getDisplayOrderNo(giftMaterialOrder)}`}
        open={Boolean(giftMaterialOrder)}
        width={isMobile ? '96%' : 620}
        onCancel={onCloseGiftMaterial}
        onOk={() => giftMaterialForm.submit()}
        okText="提交资料"
        destroyOnHidden
      >
        <Typography.Paragraph type="secondary">
          请填写本人游戏账号信息并上传主页截图；后台核对后会添加好友，好友冷却结束后才能赠送。
        </Typography.Paragraph>
        <Form form={giftMaterialForm} layout="vertical" onFinish={onSubmitGiftMaterial}>
          <Form.Item
            label="游戏昵称"
            name="gameNickname"
            rules={[{ required: true, whitespace: true, message: '请填写游戏昵称' }]}
          >
            <Input placeholder="本人游戏昵称" maxLength={50} />
          </Form.Item>
          <Form.Item
            label="游戏ID"
            name="gameId"
            rules={[{ required: true, whitespace: true, message: '请填写游戏ID' }]}
          >
            <Input placeholder="本人游戏ID" maxLength={50} />
          </Form.Item>
          <Form.Item
            label="区服"
            name="serverZone"
            rules={[{ required: true, whitespace: true, message: '请填写区服' }]}
          >
            <Input placeholder="例如：QQ区 / 微信区 / 具体区服名称" maxLength={50} />
          </Form.Item>
          <Form.Item label="系统" name="system" initialValue="">
            <Radio.Group>
              <Radio.Button value="">不区分</Radio.Button>
              <Radio.Button value="安卓">安卓</Radio.Button>
              <Radio.Button value="苹果">苹果</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            label="主页截图"
            required
            extra="至少上传一张本人游戏主页截图，供后台核对身份。"
          >
            <ImageUpload
              scene="worker-gift-material"
              scope="worker"
              value={giftMaterialFiles}
              onChange={onGiftMaterialFilesChange}
              maxCount={5}
              showPasteHint
            />
          </Form.Item>
          <Form.Item label="备注" name="note">
            <Input.TextArea rows={2} maxLength={200} showCount placeholder="选填" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
