import {
  ArrowUpOutlined,
  ContactsOutlined,
  FileDoneOutlined,
  ReloadOutlined,
  RiseOutlined,
  TeamOutlined,
  ThunderboltOutlined,
  UserAddOutlined,
} from '@ant-design/icons';
import type { ReactNode } from 'react';
import {
  App as AntdApp,
  Button,
  Card,
  Col,
  Row,
  Statistic,
  Table,
  Tag,
  Timeline,
} from 'antd';
import type { TableProps } from 'antd';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import { PERMISSION } from '@/constants/permissions';
import { useAuthStore } from '@/store/auth';
import './Dashboard.scss';

interface OrderRecord {
  key: string;
  id: string;
  customer: string;
  amount: number;
  status: 'completed' | 'pending' | 'cancelled';
  createdAt: string;
}

interface StatItem {
  title: string;
  value: number;
  delta: string;
  icon: ReactNode;
  color: string;
  background: string;
  prefix?: string;
}

const stats: StatItem[] = [
  {
    title: '客户总数',
    value: 2864,
    delta: '+12.5%',
    icon: <TeamOutlined />,
    color: '#4f46e5',
    background: '#eef2ff',
  },
  {
    title: '本月新增客户',
    value: 328,
    delta: '+8.2%',
    icon: <UserAddOutlined />,
    color: '#0284c7',
    background: '#e0f2fe',
  },
  {
    title: '本月订单',
    value: 1268,
    delta: '+21.4%',
    icon: <FileDoneOutlined />,
    color: '#059669',
    background: '#d1fae5',
  },
  {
    title: '本月销售额',
    value: 286450,
    delta: '+16.8%',
    icon: <RiseOutlined />,
    color: '#d97706',
    background: '#fef3c7',
    prefix: '¥',
  },
];

const quickLinks = [
  {
    title: '用户管理',
    description: '账号、角色与状态',
    path: '/system/users',
    permission: PERMISSION.USER_VIEW,
    icon: <TeamOutlined />,
    color: '#4f46e5',
    background: '#eef2ff',
  },
  {
    title: '订单管理',
    description: '查看与处理订单',
    path: '/business/orders',
    permission: PERMISSION.ORDER_VIEW,
    icon: <FileDoneOutlined />,
    color: '#0284c7',
    background: '#e0f2fe',
  },
  {
    title: '客户管理',
    description: '维护客户资料',
    path: '/business/customers',
    permission: PERMISSION.CUSTOMER_VIEW,
    icon: <ContactsOutlined />,
    color: '#d97706',
    background: '#fef3c7',
  },
  {
    title: '按钮权限',
    description: '权限码演示',
    path: '/system/permission/button',
    permission: PERMISSION.PERMISSION_BUTTON,
    icon: <ThunderboltOutlined />,
    color: '#7c3aed',
    background: '#f3e8ff',
  },
];

const recentOrders: OrderRecord[] = [
  {
    key: '1',
    id: 'SO20261017001',
    customer: '杭州云启科技有限公司',
    amount: 28600,
    status: 'completed',
    createdAt: '2026-10-17 09:42',
  },
  {
    key: '2',
    id: 'SO20261016008',
    customer: '上海灵犀网络科技',
    amount: 15800,
    status: 'pending',
    createdAt: '2026-10-16 18:20',
  },
  {
    key: '3',
    id: 'SO20261016005',
    customer: '深圳前海智造有限公司',
    amount: 63200,
    status: 'completed',
    createdAt: '2026-10-16 15:08',
  },
  {
    key: '4',
    id: 'SO20261015012',
    customer: '北京星辰数据服务',
    amount: 9600,
    status: 'cancelled',
    createdAt: '2026-10-15 11:36',
  },
  {
    key: '5',
    id: 'SO20261015003',
    customer: '成都锦江数字科技',
    amount: 41200,
    status: 'completed',
    createdAt: '2026-10-15 09:15',
  },
];

const statusMap: Record<OrderRecord['status'], { text: string; color: string }> = {
  completed: { text: '已完成', color: 'success' },
  pending: { text: '处理中', color: 'processing' },
  cancelled: { text: '已取消', color: 'default' },
};

const columns: TableProps<OrderRecord>['columns'] = [
  {
    title: '订单号',
    dataIndex: 'id',
    render: (value: string) => <span className="dashboard-order-id">{value}</span>,
  },
  { title: '客户', dataIndex: 'customer', ellipsis: true },
  {
    title: '金额',
    dataIndex: 'amount',
    align: 'right',
    render: (value: number) => <strong>¥{value.toLocaleString()}</strong>,
  },
  {
    title: '状态',
    dataIndex: 'status',
    render: (status: OrderRecord['status']) => (
      <Tag color={statusMap[status].color} bordered={false}>
        {statusMap[status].text}
      </Tag>
    ),
  },
  { title: '创建时间', dataIndex: 'createdAt', width: 160 },
];

const timelineItems = [
  {
    color: 'green',
    children: (
      <div className="dashboard-activity">
        <p>
          <strong>新订单</strong> 来自「杭州云启科技」
        </p>
        <span>10 分钟前</span>
      </div>
    ),
  },
  {
    color: 'blue',
    children: (
      <div className="dashboard-activity">
        <p>
          <strong>新增客户</strong> 深圳前海智造有限公司
        </p>
        <span>1 小时前</span>
      </div>
    ),
  },
  {
    color: 'purple',
    children: (
      <div className="dashboard-activity">
        <p>
          <strong>权限变更</strong> 销售组已更新角色
        </p>
        <span>3 小时前</span>
      </div>
    ),
  },
  {
    color: 'gray',
    children: (
      <div className="dashboard-activity">
        <p>
          <strong>系统维护</strong> 数据备份已完成
        </p>
        <span>昨天 23:30</span>
      </div>
    ),
  },
];

export default function Dashboard() {
  const navigate = useNavigate();
  const user = useAuthStore((state) => state.user);
  const hasPermission = useAuthStore((state) => state.hasPermission);
  const { message } = AntdApp.useApp();

  const hour = dayjs().hour();
  const greeting = hour < 12 ? '早上好' : hour < 18 ? '下午好' : '晚上好';

  const visibleQuickLinks = quickLinks.filter(
    (link) => !link.permission || hasPermission(link.permission),
  );

  return (
    <div className="dashboard-page">
      <div className="page-header">
        <div>
          <h1 className="page-header__title">
            {greeting}，{user?.nickname} 👋
          </h1>
          <p className="page-header__desc">
            今天是 {dayjs().format('YYYY年MM月DD日 dddd')}，这是 CRM 运营概览。
          </p>
        </div>
        <div className="page-header__actions">
          <Tag color="purple" bordered={false}>
            演示数据
          </Tag>
          <Button icon={<ReloadOutlined />} onClick={() => message.success('数据已刷新')}>
            刷新数据
          </Button>
        </div>
      </div>

      <Row gutter={[16, 16]}>
        {stats.map((stat) => (
          <Col key={stat.title} xs={24} sm={12} xl={6}>
            <Card className="stat-card" variant="borderless">
              <div className="stat-card__top">
                <span className="stat-card__title">{stat.title}</span>
                <span
                  className="stat-card__icon"
                  style={{ color: stat.color, background: stat.background }}
                >
                  {stat.icon}
                </span>
              </div>
              <Statistic
                value={stat.value}
                prefix={stat.prefix}
                groupSeparator=","
                valueStyle={{ fontSize: 28, fontWeight: 700, color: 'var(--app-text)' }}
              />
              <div className="stat-card__delta">
                <ArrowUpOutlined />
                <span>{stat.delta}</span>
                <em>较上月</em>
              </div>
            </Card>
          </Col>
        ))}
      </Row>

      <Row gutter={[16, 16]} className="dashboard-row">
        <Col xs={24} lg={15}>
          <Card
            className="dashboard-card"
            variant="borderless"
            title="快捷入口"
            extra={<span className="text-muted">常用功能</span>}
          >
            <div className="quick-grid">
              {visibleQuickLinks.map((link) => (
                <button
                  key={link.path}
                  type="button"
                  className="quick-link"
                  onClick={() => navigate(link.path)}
                >
                  <span
                    className="quick-link__icon"
                    style={{ color: link.color, background: link.background }}
                  >
                    {link.icon}
                  </span>
                  <span className="quick-link__text">
                    <strong>{link.title}</strong>
                    <small>{link.description}</small>
                  </span>
                </button>
              ))}
            </div>
          </Card>
        </Col>

        <Col xs={24} lg={9}>
          <Card className="dashboard-card" variant="borderless" title="系统动态">
            <Timeline items={timelineItems} />
          </Card>
        </Col>
      </Row>

      <Card
        className="dashboard-card dashboard-orders"
        variant="borderless"
        title="最近订单"
        extra={
          <Button type="link" onClick={() => navigate('/business/orders')}>
            查看全部
          </Button>
        }
      >
        <Table<OrderRecord>
          rowKey="key"
          columns={columns}
          dataSource={recentOrders}
          pagination={false}
          scroll={{ x: 680 }}
        />
      </Card>
    </div>
  );
}
