import {
  Alert,
  DatePicker,
  Descriptions,
  Form,
  Image,
  Input,
  InputNumber,
  Modal,
  Select,
  Space,
  Typography,
} from 'antd'
import type { FormInstance } from 'antd'

import ImageUpload from '@/components/files/ImageUpload'
import type {
  UploadedFile,
  WorkerFinanceConfig,
  WorkerProfileSummary,
  WorkerUser,
  WorkerWithdrawalAccount,
} from '@/types/worker-platform'

import {
  formatMoney,
  formatWithdrawChannel,
  hasRechargeConfig,
  resolveAvailableForWithdraw,
} from './worker-profile-view-utils'

type RechargeFormValues = {
  amount?: number
  note?: string
  paidAt?: string
  proofFiles?: UploadedFile[]
}

type WithdrawFormValues = {
  amount?: number
  accountChannel?: string
  note?: string
}

type WithdrawalAccountFormValues = {
  accountChannel?: string
  accountName?: string
  accountNo?: string
  alipayQrCodeImages?: UploadedFile[]
  wechatQrCodeImages?: UploadedFile[]
}

type AlipayQrCodeFormValues = {
  alipayQrCodeImages?: UploadedFile[]
}

export function WorkerProfileFinanceModals({
  isMobile,
  worker,
  summary,
  financeConfig,
  withdrawalAccounts,
  selectedWithdrawalAccount,
  selectedWithdrawChannel,
  selectedWithdrawalAccountChannel,
  rechargeOpen,
  setRechargeOpen,
  submittingRecharge,
  rechargeForm,
  submitRecharge,
  withdrawalAccountOpen,
  setWithdrawalAccountOpen,
  submittingWithdrawalAccount,
  withdrawalAccountForm,
  submitWithdrawalAccount,
  alipayQrCodeOpen,
  setAlipayQrCodeOpen,
  alipayQrCodeForm,
  submitAlipayQrCode,
  withdrawOpen,
  setWithdrawOpen,
  submittingWithdraw,
  withdrawForm,
  submitWithdraw,
}: {
  isMobile: boolean
  worker: WorkerUser | undefined
  summary: WorkerProfileSummary | undefined
  financeConfig: WorkerFinanceConfig | undefined
  withdrawalAccounts: WorkerWithdrawalAccount[]
  selectedWithdrawalAccount: WorkerWithdrawalAccount | undefined
  selectedWithdrawChannel: string | undefined
  selectedWithdrawalAccountChannel: string | undefined
  rechargeOpen: boolean
  setRechargeOpen: (open: boolean) => void
  submittingRecharge: boolean
  rechargeForm: FormInstance<RechargeFormValues>
  submitRecharge: (values: RechargeFormValues) => Promise<void>
  withdrawalAccountOpen: boolean
  setWithdrawalAccountOpen: (open: boolean) => void
  submittingWithdrawalAccount: boolean
  withdrawalAccountForm: FormInstance<WithdrawalAccountFormValues>
  submitWithdrawalAccount: (values: WithdrawalAccountFormValues) => Promise<void>
  alipayQrCodeOpen: boolean
  setAlipayQrCodeOpen: (open: boolean) => void
  alipayQrCodeForm: FormInstance<AlipayQrCodeFormValues>
  submitAlipayQrCode: (values: AlipayQrCodeFormValues) => Promise<void>
  withdrawOpen: boolean
  setWithdrawOpen: (open: boolean) => void
  submittingWithdraw: boolean
  withdrawForm: FormInstance<WithdrawFormValues>
  submitWithdraw: (values: WithdrawFormValues) => Promise<void>
}) {
  return (
    <>
      <Modal
        title="充值申请"
        open={rechargeOpen}
        width={isMobile ? '92%' : 540}
        destroyOnHidden
        confirmLoading={submittingRecharge}
        onCancel={() => {
          setRechargeOpen(false)
          rechargeForm.resetFields()
        }}
        onOk={() => rechargeForm.submit()}
      >
        <Form
          form={rechargeForm}
          layout="vertical"
          initialValues={{ amount: undefined, note: '' }}
          onFinish={submitRecharge}
        >
          <Alert
            showIcon
            type={hasRechargeConfig(financeConfig) ? 'info' : 'warning'}
            message={
              hasRechargeConfig(financeConfig)
                ? '请先按下方收款信息完成转账，再提交充值申请，管理员核对后会手动入账。'
                : '管理员暂未配置完整收款信息，如无法转账请先联系管理员确认。'
            }
          />
          <Space
            direction="vertical"
            size={12}
            className="full-width"
            style={{ marginTop: 16, marginBottom: 16 }}
          >
            {financeConfig?.recharge.qrCodeImage ? (
              <Image
                width={180}
                src={
                  financeConfig.recharge.qrCodeImage.mediumUrl ||
                  financeConfig.recharge.qrCodeImage.url
                }
              />
            ) : null}
            <Descriptions column={1} bordered size="small">
              <Descriptions.Item label="收款通道">
                {financeConfig?.recharge.channelName || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="收款人">
                {financeConfig?.recharge.accountName || '-'}
              </Descriptions.Item>
              <Descriptions.Item label="收款账号">
                {financeConfig?.recharge.accountNo ? (
                  <Typography.Text copyable>{financeConfig.recharge.accountNo}</Typography.Text>
                ) : (
                  '-'
                )}
              </Descriptions.Item>
              <Descriptions.Item label="充值说明">
                {financeConfig?.recharge.instructions || '请转账后填写备注说明，方便管理员核对。'}
              </Descriptions.Item>
            </Descriptions>
          </Space>
          <Form.Item
            label="充值金额"
            name="amount"
            rules={[{ required: true, message: '请输入充值金额' }]}
          >
            <InputNumber min={0.01} step={1} addonAfter="元" className="full-width" />
          </Form.Item>
          <Form.Item
            label="付款时间"
            name="paidAt"
            rules={[{ required: true, message: '请选择付款时间' }]}
          >
            <DatePicker
              showTime
              style={{ width: '100%' }}
              placeholder="选择转账完成时间"
              format="YYYY-MM-DD HH:mm"
            />
          </Form.Item>
          <Form.Item
            label="付款凭证"
            name="proofFiles"
            extra="上传转账成功截图，便于管理员快速核对入账"
          >
            <ImageUpload scene="worker-finance-proof" scope="worker" maxCount={5} />
          </Form.Item>
          <Form.Item label="备注说明" name="note">
            <Input.TextArea
              rows={4}
              placeholder="填写转账备注、支付时间、截图说明等，方便管理员尽快核对。"
            />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="添加提现信息"
        open={withdrawalAccountOpen}
        width={isMobile ? '92%' : 500}
        destroyOnHidden
        confirmLoading={submittingWithdrawalAccount}
        onCancel={() => {
          setWithdrawalAccountOpen(false)
          withdrawalAccountForm.resetFields()
        }}
        onOk={() => withdrawalAccountForm.submit()}
      >
        <Alert
          showIcon
          type="warning"
          message="支付宝和微信可分别添加一次；收款人姓名和账号添加后不可自行修改。历史支付宝账户缺少二维码时，仅可补充一次。"
          style={{ marginBottom: 16 }}
        />
        <Form form={withdrawalAccountForm} layout="vertical" onFinish={submitWithdrawalAccount}>
          <Form.Item
            label="提现方式"
            name="accountChannel"
            rules={[{ required: true, message: '请选择提现方式' }]}
          >
            <Select
              options={[
                ...(!withdrawalAccounts.some((account) => account.accountChannel === 'alipay')
                  ? [{ value: 'alipay', label: '支付宝' }]
                  : []),
                ...(!withdrawalAccounts.some((account) => account.accountChannel === 'wechat')
                  ? [{ value: 'wechat', label: '微信收款（仅支持 100 元及以下提现）' }]
                  : []),
              ]}
            />
          </Form.Item>
          <Form.Item
            label="收款人姓名"
            name="accountName"
            rules={[{ required: true, message: '请输入收款人姓名' }]}
          >
            <Input placeholder="请输入真实姓名" />
          </Form.Item>
          {selectedWithdrawalAccountChannel === 'wechat' ? (
            <Form.Item
              label="微信收款二维码"
              name="wechatQrCodeImages"
              rules={[{ required: true, message: '请上传微信收款二维码' }]}
              extra="微信提现仅使用收款二维码，不需要填写微信账号。"
            >
              <ImageUpload scene="worker-withdrawal-wechat-qr" scope="worker" maxCount={1} />
            </Form.Item>
          ) : (
            <>
              <Form.Item
                label="支付宝账号"
                name="accountNo"
                rules={[{ required: true, message: '请输入支付宝账号' }]}
              >
                <Input placeholder="请输入支付宝账号" />
              </Form.Item>
              <Form.Item
                label="支付宝收款二维码"
                name="alipayQrCodeImages"
                rules={[{ required: true, message: '请上传支付宝收款二维码' }]}
              >
                <ImageUpload scene="worker-withdrawal-alipay-qr" scope="worker" maxCount={1} />
              </Form.Item>
            </>
          )}
        </Form>
      </Modal>

      <Modal
        title="补充支付宝收款二维码"
        open={alipayQrCodeOpen}
        width={isMobile ? '92%' : 500}
        destroyOnHidden
        onCancel={() => {
          setAlipayQrCodeOpen(false)
          alipayQrCodeForm.resetFields()
        }}
        onOk={() => alipayQrCodeForm.submit()}
      >
        <Alert
          showIcon
          type="info"
          message="历史账户仅可补充一次支付宝收款二维码，保存后不可自行修改；已登记的收款人姓名和账号保持锁定。"
          style={{ marginBottom: 16 }}
        />
        <Form form={alipayQrCodeForm} layout="vertical" onFinish={submitAlipayQrCode}>
          <Form.Item
            label="支付宝收款二维码"
            name="alipayQrCodeImages"
            rules={[{ required: true, message: '请上传支付宝收款二维码' }]}
          >
            <ImageUpload scene="worker-withdrawal-alipay-qr" scope="worker" maxCount={1} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="提现申请"
        open={withdrawOpen}
        width={isMobile ? '92%' : 540}
        destroyOnHidden
        confirmLoading={submittingWithdraw}
        onCancel={() => {
          setWithdrawOpen(false)
          withdrawForm.resetFields()
        }}
        onOk={() => withdrawForm.submit()}
      >
        <Form form={withdrawForm} layout="vertical" onFinish={submitWithdraw}>
          {financeConfig?.withdraw.instructions ? (
            <Alert
              showIcon
              type="info"
              message={financeConfig.withdraw.instructions}
              style={{ marginBottom: 16 }}
            />
          ) : null}
          <Alert
            showIcon
            type="warning"
            message={`每天最多提现 3 次（支付宝、微信共享次数）；100 元及以下支持微信和支付宝，超过 100 元仅支持支付宝；验收报酬与押金需 ${Number(financeConfig?.depositUnfreezeDays ?? 3)} 天解冻到账后方可提现。`}
            style={{ marginBottom: 16 }}
          />
          <Descriptions column={1} bordered size="small" style={{ marginBottom: 16 }}>
            <Descriptions.Item label="提现账户">
              {formatWithdrawChannel(selectedWithdrawalAccount?.accountChannel || '')} ·{' '}
              {selectedWithdrawalAccount?.accountName || '-'} ·{' '}
              {selectedWithdrawalAccount?.accountChannel === 'wechat'
                ? '收款二维码'
                : selectedWithdrawalAccount?.accountNoMasked || '-'}
            </Descriptions.Item>
          </Descriptions>
          <Form.Item label="可提现余额">
            <Typography.Text strong>
              {formatMoney(resolveAvailableForWithdraw(worker, summary))}
            </Typography.Text>
          </Form.Item>
          <Form.Item
            label="提现方式"
            name="accountChannel"
            rules={[{ required: true, message: '请选择提现方式' }]}
          >
            <Select
              options={withdrawalAccounts.map((account) => ({
                value: account.accountChannel,
                label:
                  account.accountChannel === 'wechat'
                    ? '微信收款 · 收款二维码'
                    : `${formatWithdrawChannel(account.accountChannel)} · ${account.accountNoMasked}`,
              }))}
            />
          </Form.Item>
          <Form.Item
            label="提现金额"
            name="amount"
            rules={[
              { required: true, message: '请输入提现金额' },
              {
                validator(_, value) {
                  return Number(value || 0) > 100 && selectedWithdrawChannel !== 'alipay'
                    ? Promise.reject(
                        new Error('超过 100 元仅支持支付宝提现，请联系客服修改提现信息'),
                      )
                    : Promise.resolve()
                },
              },
            ]}
          >
            <InputNumber min={0.01} step={1} addonAfter="元" className="full-width" />
          </Form.Item>
          <Form.Item label="备注说明" name="note">
            <Input.TextArea rows={4} placeholder="可补充到账要求、手机号、开户行等说明。" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}
