import { useQuery, useQueryClient } from '@tanstack/react-query'
import { App, Alert, Button, Card, Space, Switch, Table, Typography } from 'antd'
import type { TableColumnsType } from 'antd'
import { useEffect, useState } from 'react'

import {
  fetchAdminWorkerPlatformNotificationConfig,
  saveAdminWorkerPlatformNotificationConfig,
} from '@/services/admin'
import type {
  WorkerPlatformNotificationConfig,
  WorkerPlatformNotificationEventKey,
} from '@/types/worker-platform'

type NotificationEventRow = {
  key: WorkerPlatformNotificationEventKey
  name: string
  description: string
}

const notificationEventRows: NotificationEventRow[] = [
  { key: 'withdraw_requested', name: '提现申请', description: '打手提交新的提现申请' },
  { key: 'recharge_requested', name: '充值申请', description: '打手提交新的充值申请' },
  { key: 'acceptance_submitted', name: '提交验收', description: '打手提交订单验收资料' },
  { key: 'acceptance_reminded', name: '催验收', description: '打手在验收后催促处理' },
  { key: 'material_required', name: '待补资料工单', description: '新工单等待后台补充资料' },
  {
    key: 'cancel_requested',
    name: '打手退单申请',
    description: '打手提交新的退单申请，等待客服审核',
  },
  { key: 'feedback_submitted', name: '问题反馈', description: '打手反馈客户资料或订单处理问题' },
]

export default function NotificationsPanel() {
  const { message } = App.useApp()
  const queryClient = useQueryClient()
  const [draft, setDraft] = useState<WorkerPlatformNotificationConfig | null>(null)
  const [saving, setSaving] = useState(false)
  const configQuery = useQuery({
    queryKey: ['admin-worker-platform-notification-config'],
    queryFn: fetchAdminWorkerPlatformNotificationConfig,
  })

  useEffect(() => {
    const config = configQuery.data?.data
    if (config) {
      setDraft(config)
    }
  }, [configQuery.data])

  function updateEvent(
    eventKey: WorkerPlatformNotificationEventKey,
    field: 'todoEnabled' | 'soundEnabled' | 'externalPushEnabled',
    value: boolean,
  ) {
    setDraft((current) => {
      if (!current) return current
      const event = current.events[eventKey]
      const nextEvent = { ...event, [field]: value }
      if (field === 'todoEnabled' && !value) {
        nextEvent.soundEnabled = false
      }
      return {
        ...current,
        events: { ...current.events, [eventKey]: nextEvent },
      }
    })
  }

  async function saveConfig() {
    if (!draft) return
    setSaving(true)
    try {
      await saveAdminWorkerPlatformNotificationConfig(draft)
      await queryClient.invalidateQueries({
        queryKey: ['admin-worker-platform-notification-config'],
      })
      message.success('通知配置已保存')
    } catch (error) {
      message.error(error instanceof Error ? error.message : '保存通知配置失败')
    } finally {
      setSaving(false)
    }
  }

  const columns: TableColumnsType<NotificationEventRow> = [
    {
      title: '通知事件',
      dataIndex: 'name',
      minWidth: 220,
      render: (_, row) => (
        <div className="cell-stack">
          <Typography.Text strong>{row.name}</Typography.Text>
          <Typography.Text type="secondary">{row.description}</Typography.Text>
        </div>
      ),
    },
    {
      title: '后台待办',
      width: 130,
      align: 'center',
      render: (_, row) => (
        <Switch
          checked={draft?.events[row.key].todoEnabled || false}
          disabled={!draft || saving}
          onChange={(checked) => updateEvent(row.key, 'todoEnabled', checked)}
        />
      ),
    },
    {
      title: '声音播报',
      width: 130,
      align: 'center',
      render: (_, row) => (
        <Switch
          checked={draft?.events[row.key].soundEnabled || false}
          disabled={!draft?.events[row.key].todoEnabled || saving}
          onChange={(checked) => updateEvent(row.key, 'soundEnabled', checked)}
        />
      ),
    },
    {
      title: 'Bark/WPush',
      width: 140,
      align: 'center',
      render: (_, row) => (
        <Switch
          checked={draft?.events[row.key].externalPushEnabled || false}
          disabled={!draft || saving}
          onChange={(checked) => updateEvent(row.key, 'externalPushEnabled', checked)}
        />
      ),
    },
  ]

  return (
    <Card size="small" bordered={false}>
      <Space direction="vertical" size={16} style={{ width: '100%' }}>
        <Alert
          type="info"
          showIcon
          message="配置仅影响保存后产生的通知"
          description="关闭后台待办后，声音播报会同步关闭；已创建的待办不会被隐藏或删除。"
        />
        <Table
          rowKey="key"
          columns={columns}
          dataSource={notificationEventRows}
          pagination={false}
          loading={configQuery.isLoading}
          scroll={{ x: 660 }}
        />
        <Space>
          <Button
            type="primary"
            loading={saving}
            disabled={!draft}
            onClick={() => void saveConfig()}
          >
            保存配置
          </Button>
          <Typography.Text type="secondary">浏览器总声音开关仍可在后台右上角控制。</Typography.Text>
        </Space>
      </Space>
    </Card>
  )
}
