import { ReloadOutlined } from '@ant-design/icons'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import { Alert, App, Button, Card, Empty, Form, Space, Tabs, Typography } from 'antd'
import { useState } from 'react'
import { useNavigate } from 'react-router'

import {
  changeWorkerPassword,
  createWorkerRechargeRequest,
  createWorkerWithdrawalAccount,
  createWorkerWithdrawRequest,
  fetchWorkerFinanceRequests,
  fetchWorkerProfile,
  fetchWorkerSessions,
  deleteWorkerSession,
  fetchWorkerWalletLedgers,
  logoutWorker,
  renameWorkerAccount,
  saveWorkerAlipayWithdrawalQrCode,
} from '@/services/worker'
import type { UploadedFile, WorkerSessionDevice } from '@/types/worker-platform'
import { formatDateTime } from '@/utils/date-time'
import { useIsMobile } from '@/utils/use-is-mobile'
import { clearWorkerSession } from '@/utils/worker-auth'
import {
  WorkerProfileAccountModals,
  type PasswordFormValues,
  type RenameFormValues,
} from './WorkerProfileAccountModals'
import { WorkerProfileFinanceModals } from './WorkerProfileFinanceModals'
import { WorkerProfileMobileView } from './WorkerProfileMobileView'
import {
  WorkerProfileDesktopAccountDetails,
  WorkerProfileDesktopActions,
  WorkerProfileDesktopIdentity,
  WorkerProfileDesktopWallet,
} from './WorkerProfileDesktopSections'
import {
  WorkerProfileDesktopLedgerRecords,
  WorkerProfileDesktopRequestRecords,
  WorkerProfileMobileLedgerRecords,
  WorkerProfileMobileRequestRecords,
} from './WorkerProfileRecords'

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 default function WorkerProfilePage() {
  const isMobile = useIsMobile()
  const { message } = App.useApp()
  const navigate = useNavigate()
  const queryClient = useQueryClient()

  const [activeTab, setActiveTab] = useState('account')
  const [ledgerPage, setLedgerPage] = useState(1)
  const [ledgerPageSize, setLedgerPageSize] = useState(10)
  const [ledgerType, setLedgerType] = useState('')
  const [requestPage, setRequestPage] = useState(1)
  const [requestPageSize, setRequestPageSize] = useState(10)
  const [requestType, setRequestType] = useState('')
  const [requestStatus, setRequestStatus] = useState('')
  const [rechargeOpen, setRechargeOpen] = useState(false)
  const [withdrawOpen, setWithdrawOpen] = useState(false)
  const [withdrawalAccountOpen, setWithdrawalAccountOpen] = useState(false)
  const [alipayQrCodeOpen, setAlipayQrCodeOpen] = useState(false)
  const [passwordOpen, setPasswordOpen] = useState(false)
  const [renameOpen, setRenameOpen] = useState(false)
  const [submittingRename, setSubmittingRename] = useState(false)
  const [renameForm] = Form.useForm<RenameFormValues>()
  const [contactOpen, setContactOpen] = useState(false)
  const [devicesOpen, setDevicesOpen] = useState(false)
  const [submittingRecharge, setSubmittingRecharge] = useState(false)
  const [submittingWithdraw, setSubmittingWithdraw] = useState(false)
  const [submittingWithdrawalAccount, setSubmittingWithdrawalAccount] = useState(false)
  const [submittingPassword, setSubmittingPassword] = useState(false)
  const [rechargeForm] = Form.useForm<RechargeFormValues>()
  const [withdrawForm] = Form.useForm<WithdrawFormValues>()
  const [withdrawalAccountForm] = Form.useForm<WithdrawalAccountFormValues>()
  const [alipayQrCodeForm] = Form.useForm<AlipayQrCodeFormValues>()
  const [passwordForm] = Form.useForm<PasswordFormValues>()
  const selectedWithdrawChannel = Form.useWatch('accountChannel', withdrawForm)
  const selectedWithdrawalAccountChannel = Form.useWatch('accountChannel', withdrawalAccountForm)

  const devicesQuery = useQuery({
    queryKey: ['worker-sessions'],
    queryFn: () => fetchWorkerSessions(),
    enabled: devicesOpen,
    retry: false,
  })

  const profileQuery = useQuery({
    queryKey: ['worker-profile'],
    queryFn: () => fetchWorkerProfile(),
    retry: false,
  })

  const worker = profileQuery.data?.data.worker
  const summary = profileQuery.data?.data.summary
  const levelProgress = profileQuery.data?.data.levelProgress
  const financeConfig = profileQuery.data?.data.financeConfig
  const withdrawalAccounts = profileQuery.data?.data.withdrawalAccounts || []
  const selectedWithdrawalAccount = withdrawalAccounts.find(
    (account) => account.accountChannel === selectedWithdrawChannel,
  )
  const alipayWithdrawalAccount = withdrawalAccounts.find(
    (account) => account.accountChannel === 'alipay',
  )
  const canUseFinanceActions = worker?.status === 'active'
  const renameCards = worker?.renameCards ?? 1
  const renameLocked =
    Boolean(worker?.renameUnlockedAt) && Date.parse(worker?.renameUnlockedAt || '') > Date.now()
  const canRename = renameCards > 0 && !renameLocked
  const renameHint = renameLocked
    ? `修改昵称后一年内不可再次修改，${formatDateTime(worker?.renameUnlockedAt || null)} 后可改`
    : renameCards <= 0
      ? '改名卡已用完'
      : `剩余改名卡 ${renameCards} 张，修改昵称后一年内不可再次修改`

  async function copyInviteCode() {
    if (!worker?.inviteCode) return
    try {
      await navigator.clipboard.writeText(worker.inviteCode)
      message.success('邀请码已复制')
    } catch {
      message.error('复制失败，请手动复制')
    }
  }

  const ledgersQuery = useQuery({
    queryKey: ['worker-wallet-ledgers', ledgerType, ledgerPage, ledgerPageSize],
    queryFn: () =>
      fetchWorkerWalletLedgers({
        page: ledgerPage,
        pageSize: ledgerPageSize,
        ledgerType,
      }),
    enabled: Boolean(worker),
    retry: false,
  })

  const requestsQuery = useQuery({
    queryKey: ['worker-finance-requests', requestType, requestStatus, requestPage, requestPageSize],
    queryFn: () =>
      fetchWorkerFinanceRequests({
        page: requestPage,
        pageSize: requestPageSize,
        requestType,
        status: requestStatus,
      }),
    enabled: Boolean(worker),
    retry: false,
  })

  async function refreshAll() {
    await Promise.all([
      queryClient.invalidateQueries({ queryKey: ['worker-profile'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-wallet-ledgers'] }),
      queryClient.invalidateQueries({ queryKey: ['worker-finance-requests'] }),
    ])
  }

  async function submitLogout() {
    try {
      await logoutWorker()
    } catch {
      // 接单端退出为无状态操作，本地清理优先。
    } finally {
      clearWorkerSession()
      message.success('已退出登录')
      void navigate('/', { replace: true })
    }
  }

  async function removeWorkerDevice(device: WorkerSessionDevice) {
    try {
      await deleteWorkerSession(device.sessionId)
      message.success('登录设备已删除')
      await devicesQuery.refetch()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '删除登录设备失败')
    }
  }

  function openRechargeModal() {
    if (!canUseFinanceActions) {
      message.warning('当前账号尚未通过审核，暂时不能发起充值申请')
      return
    }
    if (financeConfig?.recharge.enabled === false) {
      message.warning('当前充值入口暂未开放，请联系管理员')
      return
    }
    setRechargeOpen(true)
  }

  function openWithdrawModal() {
    if (!canUseFinanceActions) {
      message.warning('当前账号尚未通过审核，暂时不能发起提现申请')
      return
    }
    if (financeConfig?.withdraw.enabled === false) {
      message.warning('当前提现入口暂未开放，请联系管理员')
      return
    }
    if (withdrawalAccounts.length === 0) {
      openWithdrawalAccountModal()
      return
    }
    if (alipayWithdrawalAccount && !alipayWithdrawalAccount.alipayQrCodeImage) {
      message.warning('请先补充支付宝收款二维码')
      openAlipayQrCodeModal()
      return
    }
    withdrawForm.setFieldValue('accountChannel', withdrawalAccounts[0].accountChannel)
    setWithdrawOpen(true)
  }

  function openWithdrawalAccountModal() {
    const nextChannel = ['alipay', 'wechat'].find(
      (channel) => !withdrawalAccounts.some((account) => account.accountChannel === channel),
    )
    if (!nextChannel) {
      message.info('支付宝和微信提现信息均已添加，修改请联系客服处理')
      return
    }
    withdrawalAccountForm.setFieldValue('accountChannel', nextChannel)
    setWithdrawalAccountOpen(true)
  }

  function openAlipayQrCodeModal() {
    if (!alipayWithdrawalAccount) {
      openWithdrawalAccountModal()
      return
    }
    alipayQrCodeForm.setFieldsValue({
      alipayQrCodeImages: alipayWithdrawalAccount.alipayQrCodeImage
        ? [alipayWithdrawalAccount.alipayQrCodeImage]
        : [],
    })
    setAlipayQrCodeOpen(true)
  }

  async function submitRecharge(values: RechargeFormValues) {
    setSubmittingRecharge(true)
    try {
      await createWorkerRechargeRequest({
        amount: values.amount,
        note: String(values.note || '').trim(),
        paidAt: values.paidAt || '',
        proofFiles: values.proofFiles || [],
      })
      message.success('充值申请已提交，请等待管理员处理')
      setRechargeOpen(false)
      rechargeForm.resetFields()
      await refreshAll()
      setRequestType('recharge')
      setRequestPage(1)
      setActiveTab('requests')
    } catch (error) {
      message.error(error instanceof Error ? error.message : '提交充值申请失败')
    } finally {
      setSubmittingRecharge(false)
    }
  }

  async function submitWithdraw(values: WithdrawFormValues) {
    setSubmittingWithdraw(true)
    try {
      await createWorkerWithdrawRequest({
        amount: values.amount,
        accountChannel: String(values.accountChannel || ''),
        note: String(values.note || '').trim(),
      })
      message.success('提现申请已提交，请等待管理员审核')
      setWithdrawOpen(false)
      withdrawForm.resetFields()
      await refreshAll()
      setRequestType('withdraw')
      setRequestPage(1)
      setActiveTab('requests')
    } catch (error) {
      message.error(error instanceof Error ? error.message : '提交提现申请失败')
    } finally {
      setSubmittingWithdraw(false)
    }
  }

  async function submitWithdrawalAccount(values: WithdrawalAccountFormValues) {
    setSubmittingWithdrawalAccount(true)
    try {
      await createWorkerWithdrawalAccount({
        accountChannel: String(values.accountChannel || ''),
        accountName: String(values.accountName || '').trim(),
        accountNo: String(values.accountNo || '').trim(),
        alipayQrCodeImages: values.alipayQrCodeImages || [],
        wechatQrCodeImages: values.wechatQrCodeImages || [],
      })
      message.success('提现信息已添加，该方式后续修改请联系客服处理')
      setWithdrawalAccountOpen(false)
      withdrawalAccountForm.resetFields()
      await refreshAll()
      withdrawForm.setFieldValue('accountChannel', String(values.accountChannel || ''))
      setWithdrawOpen(true)
    } catch (error) {
      message.error(error instanceof Error ? error.message : '添加提现信息失败')
    } finally {
      setSubmittingWithdrawalAccount(false)
    }
  }

  async function submitAlipayQrCode(values: AlipayQrCodeFormValues) {
    try {
      await saveWorkerAlipayWithdrawalQrCode({
        alipayQrCodeImages: values.alipayQrCodeImages || [],
      })
      message.success('支付宝收款二维码已保存')
      setAlipayQrCodeOpen(false)
      alipayQrCodeForm.resetFields()
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '保存支付宝收款二维码失败')
    }
  }

  async function submitRename(values: RenameFormValues) {
    setSubmittingRename(true)
    try {
      const response = await renameWorkerAccount({
        displayName: String(values.displayName || '').trim(),
      })
      message.success(`昵称已修改为「${response.data.worker.displayName}」，一年内无法再次修改`)
      setRenameOpen(false)
      renameForm.resetFields()
      await refreshAll()
    } catch (error) {
      message.error(error instanceof Error ? error.message : '修改昵称失败')
    } finally {
      setSubmittingRename(false)
    }
  }

  async function submitPasswordChange(values: PasswordFormValues) {
    setSubmittingPassword(true)
    try {
      await changeWorkerPassword({
        currentPassword: String(values.currentPassword || ''),
        newPassword: String(values.newPassword || ''),
      })
      message.success('密码已修改，请重新登录')
      clearWorkerSession()
      void navigate('/', { replace: true })
    } catch (error) {
      message.error(error instanceof Error ? error.message : '修改密码失败')
    } finally {
      setSubmittingPassword(false)
    }
  }

  if (profileQuery.error) {
    return (
      <section className="page-stack">
        <div className="worker-page-head">
          <Typography.Title level={3}>个人中心</Typography.Title>
          <Button
            icon={<ReloadOutlined />}
            loading={profileQuery.isFetching}
            onClick={() => refreshAll()}
          >
            刷新
          </Button>
        </div>
        <Card>
          <Typography.Text type="danger">
            {profileQuery.error instanceof Error ? profileQuery.error.message : '读取个人中心失败'}
          </Typography.Text>
        </Card>
      </section>
    )
  }

  return (
    <>
      {isMobile ? (
        !worker && !profileQuery.isLoading ? (
          <div className="worker-profile-mobile-page">
            <Empty description="暂无打手信息" />
          </div>
        ) : worker ? (
          <WorkerProfileMobileView
            worker={worker}
            summary={summary}
            levelProgress={levelProgress}
            canUseFinanceActions={canUseFinanceActions}
            needsAlipayQrCode={Boolean(
              alipayWithdrawalAccount && !alipayWithdrawalAccount.alipayQrCodeImage,
            )}
            activeTab={activeTab}
            loading={profileQuery.isFetching || ledgersQuery.isFetching || requestsQuery.isFetching}
            ledgerRecords={
              <WorkerProfileMobileLedgerRecords
                data={ledgersQuery.data}
                error={ledgersQuery.error}
                loading={ledgersQuery.isLoading}
                refreshing={ledgersQuery.isFetching}
                ledgerType={ledgerType}
                onLedgerTypeChange={(nextType) => {
                  setLedgerType(nextType)
                  setLedgerPage(1)
                }}
                onReload={() => {
                  void ledgersQuery.refetch()
                }}
                page={ledgerPage}
                pageSize={ledgerPageSize}
                onPageChange={(nextPage, nextPageSize) => {
                  setLedgerPage(nextPage)
                  setLedgerPageSize(nextPageSize)
                }}
              />
            }
            requestRecords={
              <WorkerProfileMobileRequestRecords
                data={requestsQuery.data}
                error={requestsQuery.error}
                loading={requestsQuery.isLoading}
                refreshing={requestsQuery.isFetching}
                requestType={requestType}
                requestStatus={requestStatus}
                onRequestTypeChange={(nextType) => {
                  setRequestType(nextType)
                  setRequestPage(1)
                }}
                onRequestStatusChange={(nextStatus) => {
                  setRequestStatus(nextStatus)
                  setRequestPage(1)
                }}
                onReload={() => {
                  void requestsQuery.refetch()
                }}
                page={requestPage}
                pageSize={requestPageSize}
                onPageChange={(nextPage, nextPageSize) => {
                  setRequestPage(nextPage)
                  setRequestPageSize(nextPageSize)
                }}
              />
            }
            onActiveTabChange={setActiveTab}
            onRefresh={() => {
              void refreshAll()
            }}
            onCopyInviteCode={copyInviteCode}
            onRecharge={openRechargeModal}
            onWithdraw={openWithdrawModal}
            onChangePassword={() => setPasswordOpen(true)}
            onRename={() => setRenameOpen(true)}
            renameDisabled={!canRename}
            onManageDevices={() => setDevicesOpen(true)}
            onContact={() => setContactOpen(true)}
            onAddAlipayQrCode={openAlipayQrCodeModal}
            onLogout={submitLogout}
          />
        ) : null
      ) : (
        <section className="page-stack">
          <div className="worker-page-head">
            <Typography.Title level={3}>个人中心</Typography.Title>
            <Button
              icon={<ReloadOutlined />}
              loading={
                profileQuery.isFetching || ledgersQuery.isFetching || requestsQuery.isFetching
              }
              onClick={() => refreshAll()}
            >
              刷新
            </Button>
          </div>

          {!worker && !profileQuery.isLoading ? <Empty description="暂无打手信息" /> : null}

          {worker ? (
            <Space direction="vertical" size={16} style={{ width: '100%' }}>
              {!canUseFinanceActions ? (
                <Alert
                  showIcon
                  type="warning"
                  message="当前账号尚未通过审核，充值申请、提现申请和接单功能暂不可用。"
                />
              ) : null}

              <WorkerProfileDesktopIdentity
                worker={worker}
                summary={summary}
                levelProgress={levelProgress}
                onCopyInviteCode={copyInviteCode}
              />

              <WorkerProfileDesktopWallet worker={worker} />

              <WorkerProfileDesktopActions
                canUseFinanceActions={canUseFinanceActions}
                canAddWithdrawalAccount={withdrawalAccounts.length < 2}
                needsAlipayQrCode={Boolean(
                  alipayWithdrawalAccount && !alipayWithdrawalAccount.alipayQrCodeImage,
                )}
                onRecharge={openRechargeModal}
                onWithdraw={openWithdrawModal}
                onAddWithdrawalAccount={openWithdrawalAccountModal}
                onAddAlipayQrCode={openAlipayQrCodeModal}
                onChangePassword={() => setPasswordOpen(true)}
                onRename={() => setRenameOpen(true)}
                renameDisabled={!canRename}
                renameHint={renameHint}
                onManageDevices={() => setDevicesOpen(true)}
                onContact={() => setContactOpen(true)}
                onLogout={submitLogout}
              />

              <Tabs
                activeKey={activeTab}
                onChange={setActiveTab}
                items={[
                  {
                    key: 'account',
                    label: '账号信息',
                    children: (
                      <WorkerProfileDesktopAccountDetails
                        worker={worker}
                        summary={summary}
                        withdrawalAccounts={withdrawalAccounts}
                        canUseFinanceActions={canUseFinanceActions}
                        onCopyInviteCode={copyInviteCode}
                        onAddWithdrawalAccount={openWithdrawalAccountModal}
                      />
                    ),
                  },
                  {
                    key: 'ledger',
                    label: '资金流水',
                    children: (
                      <WorkerProfileDesktopLedgerRecords
                        data={ledgersQuery.data}
                        error={ledgersQuery.error}
                        loading={ledgersQuery.isLoading}
                        refreshing={ledgersQuery.isFetching}
                        ledgerType={ledgerType}
                        onLedgerTypeChange={(nextType) => {
                          setLedgerType(nextType)
                          setLedgerPage(1)
                        }}
                        onReload={() => {
                          void ledgersQuery.refetch()
                        }}
                        page={ledgerPage}
                        pageSize={ledgerPageSize}
                        onPageChange={(nextPage, nextPageSize) => {
                          setLedgerPage(nextPage)
                          setLedgerPageSize(nextPageSize)
                        }}
                      />
                    ),
                  },
                  {
                    key: 'requests',
                    label: '申请记录',
                    children: (
                      <WorkerProfileDesktopRequestRecords
                        data={requestsQuery.data}
                        error={requestsQuery.error}
                        loading={requestsQuery.isLoading}
                        refreshing={requestsQuery.isFetching}
                        requestType={requestType}
                        requestStatus={requestStatus}
                        onRequestTypeChange={(nextType) => {
                          setRequestType(nextType)
                          setRequestPage(1)
                        }}
                        onRequestStatusChange={(nextStatus) => {
                          setRequestStatus(nextStatus)
                          setRequestPage(1)
                        }}
                        onReload={() => {
                          void requestsQuery.refetch()
                        }}
                        page={requestPage}
                        pageSize={requestPageSize}
                        onPageChange={(nextPage, nextPageSize) => {
                          setRequestPage(nextPage)
                          setRequestPageSize(nextPageSize)
                        }}
                      />
                    ),
                  },
                ]}
              />
            </Space>
          ) : null}
        </section>
      )}

      <WorkerProfileFinanceModals
        isMobile={isMobile}
        worker={worker}
        summary={summary}
        financeConfig={financeConfig}
        withdrawalAccounts={withdrawalAccounts}
        selectedWithdrawalAccount={selectedWithdrawalAccount}
        selectedWithdrawChannel={selectedWithdrawChannel}
        selectedWithdrawalAccountChannel={selectedWithdrawalAccountChannel}
        rechargeOpen={rechargeOpen}
        setRechargeOpen={setRechargeOpen}
        submittingRecharge={submittingRecharge}
        rechargeForm={rechargeForm}
        submitRecharge={submitRecharge}
        withdrawalAccountOpen={withdrawalAccountOpen}
        setWithdrawalAccountOpen={setWithdrawalAccountOpen}
        submittingWithdrawalAccount={submittingWithdrawalAccount}
        withdrawalAccountForm={withdrawalAccountForm}
        submitWithdrawalAccount={submitWithdrawalAccount}
        alipayQrCodeOpen={alipayQrCodeOpen}
        setAlipayQrCodeOpen={setAlipayQrCodeOpen}
        alipayQrCodeForm={alipayQrCodeForm}
        submitAlipayQrCode={submitAlipayQrCode}
        withdrawOpen={withdrawOpen}
        setWithdrawOpen={setWithdrawOpen}
        submittingWithdraw={submittingWithdraw}
        withdrawForm={withdrawForm}
        submitWithdraw={submitWithdraw}
      />

      <WorkerProfileAccountModals
        isMobile={isMobile}
        worker={worker}
        financeConfig={financeConfig}
        devicesOpen={devicesOpen}
        setDevicesOpen={setDevicesOpen}
        devices={devicesQuery.data?.data.items || []}
        maxDevices={devicesQuery.data?.data.maxDevices || 3}
        deviceCounts={devicesQuery.data?.data.deviceCounts || { pc: 0, mobile: 0 }}
        devicesLoading={devicesQuery.isLoading || devicesQuery.isFetching}
        removeWorkerDevice={removeWorkerDevice}
        passwordOpen={passwordOpen}
        setPasswordOpen={setPasswordOpen}
        submittingPassword={submittingPassword}
        passwordForm={passwordForm}
        submitPasswordChange={submitPasswordChange}
        contactOpen={contactOpen}
        setContactOpen={setContactOpen}
        renameOpen={renameOpen}
        setRenameOpen={setRenameOpen}
        submittingRename={submittingRename}
        renameForm={renameForm}
        submitRename={submitRename}
      />
    </>
  )
}
