import { LinkOutlined } from '@ant-design/icons';
import { PageHeader } from '@ant-design/pro-layout';
import { request, useParams } from '@umijs/max';
import { App, Button, Card, List } from 'antd';
import React, { useEffect, useState } from 'react';

// 定义链接项的类型
interface LinkItem {
  title: string;
  url: string;
}

const LinksPage: React.FC = () => {
  const { siteId } = useParams<{ siteId: string }>();
  const { message: antMessage } = App.useApp();
  const [links, setLinks] = useState<LinkItem[]>([]);
  const [loading, setLoading] = useState<boolean>(true);

  // 获取链接列表的函数
  const fetchLinks = async () => {
    if (!siteId) return;

    setLoading(true);
    try {
      const response = await request(`/site-api/${siteId}/links`);
      if (response.success && response.data) {
        setLinks(response.data);
      } else {
        antMessage.error(response.message || '获取链接列表失败');
      }
    } catch (error) {
      antMessage.error('获取链接列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 页面加载时获取链接列表
  useEffect(() => {
    fetchLinks();
  }, [siteId]);

  // 处理链接点击事件，在新标签页打开
  const handleLinkClick = (url: string) => {
    window.open(url, '_blank', 'noopener,noreferrer');
  };

  return (
    <div>
      <PageHeader title="站点链接" breadcrumb={{ items: [] }} />
      <Card
        title="常用链接"
        bordered={false}
        extra={
          <Button type="primary" onClick={fetchLinks} loading={loading}>
            刷新列表
          </Button>
        }
      >
        <List
          loading={loading}
          dataSource={links}
          renderItem={(item) => (
            <List.Item
              key={item.title}
              actions={[
                <Button
                  key={`visit-${item.title}`}
                  type="link"
                  icon={<LinkOutlined />}
                  onClick={() => handleLinkClick(item.url)}
                  target="_blank"
                >
                  访问
                </Button>,
              ]}
            >
              <List.Item.Meta
                title={item.title}
                description={
                  <a
                    href={item.url}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{ color: '#1890ff' }}
                  >
                    {item.url}
                  </a>
                }
              />
            </List.Item>
          )}
        />
      </Card>
    </div>
  );
};

export default LinksPage;
