import { useCallback, useEffect, useState } from 'react'
import {
  Button,
  Input,
  Popconfirm,
  Select,
  Space,
  Table,
  Tag,
  message,
  type TableColumnsType,
  type TablePaginationConfig,
} from 'antd'
import {
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  ReloadOutlined,
  SafetyOutlined,
  SearchOutlined,
} from '@ant-design/icons'
import { PageHeader } from '@/components/common'
import { PageEmpty, PageError } from '@/components/feedback'
import { PageLayout, FilterCard, TableCard } from '@/components/layout'
import { getErrorMessage } from '@/lib/errors'
import { deleteRole, listRoles, updateRoleStatus } from '@/services/roles'
import { RoleStatusColor, RoleStatusText, type Role, type RoleStatus } from '@/types/role'
import { RoleFormModal } from './RoleFormModal'
import { RolePermissionsModal } from './RolePermissionsModal'

export function RolesPage() {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [roles, setRoles] = useState<Role[]>([])
  const [total, setTotal] = useState(0)
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)
  const [keyword, setKeyword] = useState('')
  const [statusFilter, setStatusFilter] = useState<RoleStatus | undefined>()
  const [formVisible, setFormVisible] = useState(false)
  const [permissionsVisible, setPermissionsVisible] = useState(false)
  const [selectedRole, setSelectedRole] = useState<Role | null>(null)

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

    try {
      const result = await listRoles({
        page,
        page_size: pageSize,
        keyword: keyword || undefined,
        status: statusFilter,
      })
      setRoles(result.items)
      setTotal(result.total)
    } catch (err) {
      setError(getErrorMessage(err, '获取角色列表失败'))
    } finally {
      setLoading(false)
    }
  }, [keyword, page, pageSize, statusFilter])

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

  // 筛选条件变化时重置到第一页
  useEffect(() => {
    setPage(1)
  }, [keyword, statusFilter])

  const handleReset = () => {
    setKeyword('')
    setStatusFilter(undefined)
    setPage(1)
  }

  const handleDelete = async (id: number) => {
    try {
      await deleteRole(id)
      message.success('角色已删除')
      await fetchRoles()
    } catch (err) {
      message.error(getErrorMessage(err, '删除角色失败'))
    }
  }

  const handleToggleStatus = async (role: Role) => {
    const nextStatus: RoleStatus = role.status === 1 ? 0 : 1

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

  const columns: TableColumnsType<Role> = [
    {
      title: '角色名称',
      dataIndex: 'name',
      key: 'name',
      width: 160,
      fixed: 'left',
    },
    {
      title: '角色代码',
      dataIndex: 'code',
      key: 'code',
      width: 180,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      width: 220,
      render: (value) => value || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: RoleStatus) => (
        <Tag color={RoleStatusColor[status]}>{RoleStatusText[status]}</Tag>
      ),
    },
    {
      title: '系统角色',
      dataIndex: 'is_system',
      key: 'is_system',
      width: 100,
      render: (value) => (value ? <Tag color="blue">系统</Tag> : '-'),
    },
    {
      title: '默认角色',
      dataIndex: 'is_default',
      key: 'is_default',
      width: 100,
      render: (value) => (value ? <Tag color="green">默认</Tag> : '-'),
    },
    {
      title: '操作',
      key: 'action',
      width: 260,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => {
              setSelectedRole(record)
              setFormVisible(true)
            }}
            disabled={record.is_system}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={<SafetyOutlined />}
            onClick={() => {
              setSelectedRole(record)
              setPermissionsVisible(true)
            }}
          >
            权限
          </Button>
          <Popconfirm
            title={record.status === 1 ? '确定禁用该角色吗？' : '确定启用该角色吗？'}
            onConfirm={() => void handleToggleStatus(record)}
          >
            <Button type="link" size="small" disabled={record.is_system}>
              {record.status === 1 ? '禁用' : '启用'}
            </Button>
          </Popconfirm>
          <Popconfirm
            title="确定删除该角色吗？"
            onConfirm={() => void handleDelete(record.id)}
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              disabled={record.is_system}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  const paginationConfig: TablePaginationConfig = {
    current: page,
    pageSize,
    total,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (value) => `共 ${value} 条`,
    onChange: (current, size) => {
      setPage(current)
      setPageSize(size)
    },
  }

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

  return (
    <PageLayout>
      <PageHeader
        title="角色管理"
        description="对齐后端分页返回，支持创建、编辑、删除、状态管理和权限分配"
        actions={(
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              setSelectedRole(null)
              setFormVisible(true)
            }}
          >
            创建角色
          </Button>
        )}
      />

      <FilterCard>
        <Space wrap size="middle">
          <Input
            placeholder="角色名称/代码"
            prefix={<SearchOutlined />}
            value={keyword}
            onChange={(event) => setKeyword(event.target.value)}
            onPressEnter={() => void fetchRoles()}
            style={{ width: 220 }}
            allowClear
          />
          <Select
            placeholder="角色状态"
            value={statusFilter}
            onChange={setStatusFilter}
            allowClear
            style={{ width: 120 }}
            options={[
              { value: 0, label: '已禁用' },
              { value: 1, label: '已启用' },
            ]}
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={() => void fetchRoles()}>
            查询
          </Button>
          <Button onClick={handleReset}>重置</Button>
          <Button icon={<ReloadOutlined />} onClick={() => void fetchRoles()}>
            刷新
          </Button>
        </Space>
      </FilterCard>

      <TableCard>
        <Table
          columns={columns}
          dataSource={roles}
          rowKey="id"
          loading={loading}
          pagination={paginationConfig}
          scroll={{ x: 1200 }}
          locale={{ emptyText: <PageEmpty description="暂无角色数据" /> }}
        />
      </TableCard>

      <RoleFormModal
        open={formVisible}
        role={selectedRole}
        onSuccess={() => {
          setFormVisible(false)
          void fetchRoles()
        }}
        onClose={() => setFormVisible(false)}
      />

      <RolePermissionsModal
        open={permissionsVisible}
        role={selectedRole}
        onSuccess={() => setPermissionsVisible(false)}
        onClose={() => setPermissionsVisible(false)}
      />
    </PageLayout>
  )
}
