import { useCallback, useEffect, useState } from 'react'
import {
  Button,
  Popconfirm,
  Segmented,
  Space,
  Spin,
  Table,
  Tag,
  Tree,
  message,
  type TableColumnsType,
  type TreeProps,
} from 'antd'
import { DeleteOutlined, EditOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons'
import { PageHeader } from '@/components/common'
import { PageEmpty, PageError } from '@/components/feedback'
import { PageLayout, TreeCard } from '@/components/layout'
import { getErrorMessage } from '@/lib/errors'
import {
  deletePermission,
  getPermissionTree,
  listPermissions,
  updatePermissionStatus,
} from '@/services/permissions'
import type { Permission, PermissionStatus } from '@/types/permission'
import {
  PermissionStatusColor,
  PermissionStatusText,
  PermissionTypeColor,
  PermissionTypeText,
} from '@/types/permission'
import { PermissionFormModal } from './PermissionFormModal'
import styles from './PermissionsPage.module.css'

type ViewMode = 'tree' | 'list'

export function PermissionsPage() {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [treePermissions, setTreePermissions] = useState<Permission[]>([])
  const [flatPermissions, setFlatPermissions] = useState<Permission[]>([])
  const [viewMode, setViewMode] = useState<ViewMode>('tree')
  const [formVisible, setFormVisible] = useState(false)
  const [selectedPermission, setSelectedPermission] = useState<Permission | null>(null)
  const [parentPermission, setParentPermission] = useState<Permission | null>(null)

  const fetchPermissions = useCallback(async () => {
    setLoading(true)
    setError(null)

    try {
      const [treeResult, listResult] = await Promise.all([
        getPermissionTree(),
        listPermissions(),
      ])
      setTreePermissions(treeResult)
      setFlatPermissions(listResult)
    } catch (err) {
      setError(getErrorMessage(err, '获取权限数据失败'))
    } finally {
      setLoading(false)
    }
  }, [])

  useEffect(() => {
    void fetchPermissions()
  }, [fetchPermissions])

  const handleCreate = () => {
    setSelectedPermission(null)
    setParentPermission(null)
    setFormVisible(true)
  }

  const handleCreateChild = (permission: Permission) => {
    setSelectedPermission(null)
    setParentPermission(permission)
    setFormVisible(true)
  }

  const handleEdit = (permission: Permission) => {
    setSelectedPermission(permission)
    setParentPermission(null)
    setFormVisible(true)
  }

  const handleDelete = async (id: number) => {
    try {
      await deletePermission(id)
      message.success('权限已删除')
      await fetchPermissions()
    } catch (err) {
      message.error(getErrorMessage(err, '删除失败'))
    }
  }

  const handleToggleStatus = async (permission: Permission) => {
    const nextStatus: PermissionStatus = permission.status === 1 ? 0 : 1

    try {
      await updatePermissionStatus(permission.id, nextStatus)
      message.success('状态已更新')
      await fetchPermissions()
    } catch (err) {
      message.error(getErrorMessage(err, '状态更新失败'))
    }
  }

  const buildTreeData = (permissions: Permission[]): TreeProps['treeData'] =>
    permissions.map((permission) => ({
      key: String(permission.id),
      title: (
        <div className={styles.treeNode}>
          <div className={styles.nodeInfo}>
            <span className={styles.nodeName}>{permission.name}</span>
            <Tag color={PermissionTypeColor[permission.type]}>
              {PermissionTypeText[permission.type]}
            </Tag>
            <span className={styles.nodeCode}>{permission.code}</span>
            <Tag color={PermissionStatusColor[permission.status]}>
              {PermissionStatusText[permission.status]}
            </Tag>
            {permission.path && (
              <span style={{ color: 'var(--color-text-muted)', fontSize: 12 }}>
                {permission.path}
              </span>
            )}
          </div>
          <div className={styles.nodeActions} onClick={(event) => event.stopPropagation()}>
            <Button type="link" size="small" icon={<PlusOutlined />} onClick={() => handleCreateChild(permission)}>
              添加子权限
            </Button>
            <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(permission)}>
              编辑
            </Button>
            <Popconfirm
              title={permission.status === 1 ? '确定禁用该权限吗？' : '确定启用该权限吗？'}
              onConfirm={() => void handleToggleStatus(permission)}
            >
              <Button type="link" size="small">
                {permission.status === 1 ? '禁用' : '启用'}
              </Button>
            </Popconfirm>
            <Popconfirm
              title="确定删除该权限吗？子权限也会被删除。"
              onConfirm={() => void handleDelete(permission.id)}
            >
              <Button type="link" size="small" danger icon={<DeleteOutlined />}>
                删除
              </Button>
            </Popconfirm>
          </div>
        </div>
      ),
      children: permission.children ? buildTreeData(permission.children) : undefined,
    }))

  const listColumns: TableColumnsType<Permission> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
    },
    {
      title: '代码',
      dataIndex: 'code',
      key: 'code',
      width: 220,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (value: Permission['type']) => (
        <Tag color={PermissionTypeColor[value]}>{PermissionTypeText[value]}</Tag>
      ),
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
      width: 220,
      render: (value) => value || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (value: PermissionStatus) => (
        <Tag color={PermissionStatusColor[value]}>{PermissionStatusText[value]}</Tag>
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 240,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button type="link" size="small" icon={<PlusOutlined />} onClick={() => handleCreateChild(record)}>
            子权限
          </Button>
          <Button type="link" size="small" icon={<EditOutlined />} onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm
            title={record.status === 1 ? '确定禁用该权限吗？' : '确定启用该权限吗？'}
            onConfirm={() => void handleToggleStatus(record)}
          >
            <Button type="link" size="small">
              {record.status === 1 ? '禁用' : '启用'}
            </Button>
          </Popconfirm>
          <Popconfirm
            title="确定删除该权限吗？"
            onConfirm={() => void handleDelete(record.id)}
          >
            <Button type="link" size="small" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  if (error) {
    return <PageError description={error} onRetry={fetchPermissions} />
  }

  return (
    <PageLayout>
      <PageHeader
        title="权限管理"
        description="支持树形和列表两种视图，统一使用真实权限接口"
        actions={(
          <Space>
            <Segmented<ViewMode>
              value={viewMode}
              onChange={(value) => setViewMode(value)}
              options={[
                { label: '树形', value: 'tree' },
                { label: '列表', value: 'list' },
              ]}
            />
            <Button icon={<ReloadOutlined />} onClick={() => void fetchPermissions()}>
              刷新
            </Button>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
              创建权限
            </Button>
          </Space>
        )}
      />

      <TreeCard>
        <Spin spinning={loading}>
          {viewMode === 'tree' ? (
            treePermissions.length > 0 ? (
              <Tree
                showLine
                defaultExpandAll
                treeData={buildTreeData(treePermissions)}
                style={{ fontSize: 14 }}
              />
            ) : (
              <PageEmpty description="暂无权限数据" />
            )
          ) : (
            <Table
              rowKey="id"
              dataSource={flatPermissions}
              columns={listColumns}
              pagination={{ pageSize: 20, showSizeChanger: true }}
              scroll={{ x: 1200 }}
              locale={{ emptyText: <PageEmpty description="暂无权限数据" /> }}
            />
          )}
        </Spin>
      </TreeCard>

      <PermissionFormModal
        open={formVisible}
        permission={selectedPermission}
        parentPermission={parentPermission}
        permissions={treePermissions}
        onSuccess={() => {
          setFormVisible(false)
          void fetchPermissions()
        }}
        onClose={() => setFormVisible(false)}
      />
    </PageLayout>
  )
}
