import {
  Alert,
  Button,
  Checkbox,
  Descriptions,
  Form,
  Image,
  Input,
  Modal,
  Space,
  Table,
  Typography,
} from 'antd'
import type { FormInstance } from 'antd'

import type { WorkerFinanceConfig, WorkerSessionDevice, WorkerUser } from '@/types/worker-platform'
import { formatDateTime } from '@/utils/date-time'
import { isWorkerPasswordStrong, WORKER_PASSWORD_RULE_MESSAGE } from '@/utils/worker-password'

import { formatMoney, formatWorkerStatus } from './worker-profile-view-utils'

export type PasswordFormValues = {
  currentPassword?: string
  newPassword?: string
  confirmPassword?: string
}

export type RenameFormValues = {
  displayName?: string
  confirmed?: boolean
}

export function WorkerProfileAccountModals({
  isMobile,
  worker,
  financeConfig,
  devicesOpen,
  setDevicesOpen,
  devices,
  maxDevices,
  deviceCounts,
  devicesLoading,
  removeWorkerDevice,
  passwordOpen,
  setPasswordOpen,
  submittingPassword,
  passwordForm,
  submitPasswordChange,
  contactOpen,
  setContactOpen,
  renameOpen,
  setRenameOpen,
  submittingRename,
  renameForm,
  submitRename,
}: {
  isMobile: boolean
  worker: WorkerUser | undefined
  financeConfig: WorkerFinanceConfig | undefined
  devicesOpen: boolean
  setDevicesOpen: (open: boolean) => void
  devices: WorkerSessionDevice[]
  maxDevices: number
  deviceCounts: { pc: number; mobile: number }
  devicesLoading: boolean
  removeWorkerDevice: (device: WorkerSessionDevice) => Promise<void>
  passwordOpen: boolean
  setPasswordOpen: (open: boolean) => void
  submittingPassword: boolean
  passwordForm: FormInstance<PasswordFormValues>
  submitPasswordChange: (values: PasswordFormValues) => Promise<void>
  contactOpen: boolean
  setContactOpen: (open: boolean) => void
  renameOpen: boolean
  setRenameOpen: (open: boolean) => void
  submittingRename: boolean
  renameForm: FormInstance<RenameFormValues>
  submitRename: (values: RenameFormValues) => Promise<void>
}) {
  return (
    <>
      <Modal
        title="登录设备"
        open={devicesOpen}
        width={isMobile ? '92%' : 720}
        destroyOnHidden
        footer={null}
        onCancel={() => setDevicesOpen(false)}
      >
        <Alert
          showIcon
          type="info"
          message={`PC 和手机分别最多同时在线 ${maxDevices} 台（当前 PC ${deviceCounts.pc} 台、手机 ${deviceCounts.mobile} 台），删除对应旧设备后才能登录。`}
        />
        <Table<WorkerSessionDevice>
          size="small"
          loading={devicesLoading}
          rowKey="sessionId"
          dataSource={devices}
          pagination={false}
          style={{ marginTop: 16 }}
          columns={[
            {
              title: '设备',
              render: (_, item) => (
                <Space direction="vertical" size={0}>
                  <Typography.Text strong>{item.deviceName || item.deviceType}</Typography.Text>
                  <Typography.Text type="secondary">{item.ipAddress || '未知 IP'}</Typography.Text>
                </Space>
              ),
            },
            { title: '最近活动', render: (_, item) => formatDateTime(item.lastSeenAt) },
            {
              title: '操作',
              width: 100,
              render: (_, item) => (
                <Button
                  danger
                  type="link"
                  disabled={item.current}
                  onClick={() => void removeWorkerDevice(item)}
                >
                  {item.current ? '当前设备' : '删除'}
                </Button>
              ),
            },
          ]}
        />
      </Modal>

      <Modal
        title="修改密码"
        open={passwordOpen}
        width={isMobile ? '92%' : 480}
        destroyOnHidden
        confirmLoading={submittingPassword}
        onCancel={() => {
          setPasswordOpen(false)
          passwordForm.resetFields()
        }}
        onOk={() => passwordForm.submit()}
      >
        <Form form={passwordForm} layout="vertical" onFinish={submitPasswordChange}>
          <Form.Item
            label="当前密码"
            name="currentPassword"
            rules={[{ required: true, message: '请输入当前密码' }]}
          >
            <Input.Password autoComplete="current-password" />
          </Form.Item>
          <Form.Item
            label="新密码"
            name="newPassword"
            rules={[
              { required: true, message: '请输入新密码' },
              {
                validator: (_, value) =>
                  !value || isWorkerPasswordStrong(value)
                    ? Promise.resolve()
                    : Promise.reject(new Error(WORKER_PASSWORD_RULE_MESSAGE)),
              },
            ]}
            extra={WORKER_PASSWORD_RULE_MESSAGE}
          >
            <Input.Password autoComplete="new-password" />
          </Form.Item>
          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请再次输入新密码' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  return !value || value === getFieldValue('newPassword')
                    ? Promise.resolve()
                    : Promise.reject(new Error('两次输入的新密码不一致'))
                },
              }),
            ]}
          >
            <Input.Password autoComplete="new-password" />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="联系管理员"
        open={contactOpen}
        width={isMobile ? '92%' : 500}
        destroyOnHidden
        footer={
          <Button type="primary" onClick={() => setContactOpen(false)}>
            我知道了
          </Button>
        }
        onCancel={() => setContactOpen(false)}
      >
        <Space direction="vertical" size={16} className="full-width">
          <Alert
            showIcon
            type="info"
            message="如需取消已接订单，请扫码联系管理员处理。充值、提现与审核问题也由后台管理员人工处理。"
          />
          {financeConfig?.adminContact?.wechatQrCodeImage ? (
            <div style={{ textAlign: 'center' }}>
              <Image
                width={200}
                src={
                  financeConfig.adminContact.wechatQrCodeImage.mediumUrl ||
                  financeConfig.adminContact.wechatQrCodeImage.url
                }
                alt="管理员微信二维码"
              />
            </div>
          ) : (
            <Typography.Text type="secondary">
              管理员暂未配置微信二维码，请按下方账号信息联系。
            </Typography.Text>
          )}
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="账号">
              <Typography.Text copyable>{worker?.username || '-'}</Typography.Text>
            </Descriptions.Item>
            <Descriptions.Item label="昵称">{worker?.displayName || '-'}</Descriptions.Item>
            <Descriptions.Item label="手机号">
              <Typography.Text copyable>{worker?.phone || '-'}</Typography.Text>
            </Descriptions.Item>
            <Descriptions.Item label="账号状态">
              {formatWorkerStatus(worker?.status || '')}
            </Descriptions.Item>
            <Descriptions.Item label="当前余额">
              {formatMoney(worker?.wallet.availableAmount)}
            </Descriptions.Item>
          </Descriptions>
          <Typography.Paragraph className="worker-profile-help-text">
            建议沟通时一起提供：申请类型、金额、订单号或转账备注、收款方式，以及当前账号信息。
          </Typography.Paragraph>
        </Space>
      </Modal>

      <Modal
        title="修改昵称"
        open={renameOpen}
        width={isMobile ? '92%' : 560}
        destroyOnHidden
        footer={null}
        onCancel={() => setRenameOpen(false)}
      >
        <Alert
          showIcon
          type="warning"
          message="修改昵称后将锁定一年"
          description={
            <Space direction="vertical" size={0}>
              <Typography.Text type="danger" strong>
                昵称修改成功后，一年内无法再次修改，请谨慎操作！
              </Typography.Text>
              <Typography.Text type="secondary">
                当前剩余改名卡 {worker?.renameCards ?? 1} 张，本次修改昵称将消耗 1 张。
              </Typography.Text>
            </Space>
          }
        />
        <Form<RenameFormValues>
          form={renameForm}
          layout="vertical"
          onFinish={(values) => void submitRename(values)}
          style={{ marginTop: 16 }}
        >
          <Form.Item label="当前昵称">
            <Typography.Text strong>
              {worker?.displayName || worker?.username || '-'}
            </Typography.Text>
          </Form.Item>
          <Form.Item
            name="displayName"
            label="新昵称"
            rules={[
              { required: true, whitespace: true, message: '请输入新的昵称' },
              { max: 32, message: '昵称最长 32 个字符' },
              {
                validator: (_, value) =>
                  value && value.trim() === String(worker?.displayName || '').trim()
                    ? Promise.reject(new Error('新昵称不能与当前昵称一致'))
                    : Promise.resolve(),
              },
            ]}
          >
            <Input allowClear placeholder="最长 32 个字符，全平台不可重复" autoComplete="off" />
          </Form.Item>
          <Form.Item
            name="confirmed"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) =>
                  value ? Promise.resolve() : Promise.reject(new Error('请先勾选确认')),
              },
            ]}
          >
            <Checkbox>我已知晓改名后将消耗 1 张改名卡，且一年内无法再次修改用户名</Checkbox>
          </Form.Item>
          <Button type="primary" block loading={submittingRename} htmlType="submit">
            确认修改昵称
          </Button>
        </Form>
      </Modal>
    </>
  )
}
