import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Input, Modal, Form, Upload, message, Space, Tag, Popconfirm, Typography, List } from 'antd';
import { PlusOutlined, SearchOutlined, DeleteOutlined, PaperClipOutlined, DownloadOutlined, FileTextOutlined } from '@ant-design/icons';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import '@wangeditor/editor/dist/css/style.css';
import axios from 'axios';
import API_BASE_URL from '../config';

const { Title, Text } = Typography;

// 封装 WangEditor 组件以适配 Ant Design Form
const MyEditor = ({ value, onChange }) => {
    const [editor, setEditor] = useState(null);
    const [html, setHtml] = useState(value || '');

    // 监听 value 变化（例如表单重置时）
    useEffect(() => {
        setHtml(value || '');
    }, [value]);

    const toolbarConfig = {};
    const editorConfig = {
        placeholder: '请输入内容...',
    };

    // 及时销毁 editor
    useEffect(() => {
        return () => {
            if (editor == null) return;
            editor.destroy();
            setEditor(null);
        };
    }, [editor]);

    return (
        <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
            <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="default"
                style={{ borderBottom: '1px solid #ccc' }}
            />
            <Editor
                defaultConfig={editorConfig}
                value={html}
                onCreated={setEditor}
                onChange={editor => {
                    const newHtml = editor.getHtml();
                    setHtml(newHtml);
                    onChange(newHtml);
                }}
                mode="default"
                style={{ height: '300px', overflowY: 'hidden' }}
            />
        </div>
    );
};

const Notifications = () => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);
    const [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 0 });
    const [keyword, setKeyword] = useState('');
    
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isDetailVisible, setIsDetailVisible] = useState(false);
    const [currentNotification, setCurrentNotification] = useState(null);
    const [form] = Form.useForm();
    const [fileList, setFileList] = useState([]);

    const user = JSON.parse(localStorage.getItem('user') || '{}');
    const isAdmin = ['super_admin', 'maintainer'].includes(user.role);

    useEffect(() => {
        fetchData();
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [pagination.current, pagination.pageSize]);

    const fetchData = async () => {
        setLoading(true);
        try {
            const token = localStorage.getItem('token');
            const response = await axios.get(`${API_BASE_URL}/api/notifications`, {
                headers: { Authorization: `Bearer ${token}` },
                params: {
                    page: pagination.current,
                    limit: pagination.pageSize,
                    keyword
                }
            });
            setData(response.data.list);
            setPagination({ ...pagination, total: response.data.total });
        } catch (error) {
            message.error('获取公告列表失败');
        } finally {
            setLoading(false);
        }
    };

    const handleSearch = () => {
        setPagination({ ...pagination, current: 1 });
        fetchData();
    };

    const handleAdd = () => {
        setCurrentNotification(null);
        form.resetFields();
        setFileList([]);
        setIsModalVisible(true);
    };

    const handleDelete = async (id) => {
        try {
            const token = localStorage.getItem('token');
            await axios.delete(`${API_BASE_URL}/api/notifications/${id}`, {
                headers: { Authorization: `Bearer ${token}` }
            });
            message.success('删除成功');
            fetchData();
        } catch (error) {
            message.error('删除失败');
        }
    };

    const handleView = async (record) => {
        try {
            const token = localStorage.getItem('token');
            const response = await axios.get(`${API_BASE_URL}/api/notifications/${record.id}`, {
                headers: { Authorization: `Bearer ${token}` }
            });
            setCurrentNotification(response.data);
            setIsDetailVisible(true);
        } catch (error) {
            message.error('获取详情失败');
        }
    };

    const handleOk = async () => {
        try {
            const values = await form.validateFields();
            const formData = new FormData();
            formData.append('title', values.title);
            formData.append('content', values.content);
            formData.append('is_top', values.is_top || false);
            
            fileList.forEach(file => {
                formData.append('files', file.originFileObj || file);
            });

            const token = localStorage.getItem('token');
            await axios.post(`${API_BASE_URL}/api/notifications`, formData, {
                headers: { 
                    Authorization: `Bearer ${token}`,
                    'Content-Type': 'multipart/form-data'
                }
            });

            message.success('发布成功');
            setIsModalVisible(false);
            fetchData();
        } catch (error) {
            console.error(error);
            message.error('发布失败');
        }
    };

    const handleDownload = async (attachment) => {
        try {
            const token = localStorage.getItem('token');
            const response = await axios.get(`${API_BASE_URL}/api/notifications/attachments/${attachment.id}/download`, {
                headers: { Authorization: `Bearer ${token}` },
                responseType: 'blob'
            });
            
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            
            // 尝试从 Content-Disposition 获取文件名
            let filename = attachment.file_name;
            const contentDisposition = response.headers['content-disposition'];
            if (contentDisposition) {
                const filenameMatch = contentDisposition.match(/filename\*=UTF-8''(.+)/);
                if (filenameMatch && filenameMatch.length === 2) {
                    filename = decodeURIComponent(filenameMatch[1]);
                }
            }
            
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
            link.remove();
        } catch (error) {
            message.error('下载失败');
        }
    };

    const columns = [
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            render: (text, record) => (
                <Space>
                    {record.is_top && <Tag color="red">置顶</Tag>}
                    <Button 
                        type="link" 
                        onClick={() => handleView(record)} 
                        style={{ padding: 0, fontWeight: 500, fontSize: '15px', height: 'auto' }}
                    >
                        {text}
                    </Button>
                </Space>
            )
        },
        {
            title: '发布人',
            dataIndex: 'publisher_real_name',
            key: 'publisher',
            width: 150,
        },
        {
            title: '发布时间',
            dataIndex: 'created_at',
            key: 'created_at',
            width: 180,
            render: (text) => new Date(text).toLocaleString()
        },
        ...(isAdmin ? [{
            title: '操作',
            key: 'action',
            width: 100,
            render: (_, record) => (
                <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
                    <Button type="link" danger icon={<DeleteOutlined />}>删除</Button>
                </Popconfirm>
            )
        }] : [])
    ];

    const uploadProps = {
        onRemove: (file) => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList);
        },
        beforeUpload: (file) => {
            setFileList(prev => [...prev, file]);
            return false;
        },
        fileList,
    };

    return (
        <div style={{ padding: '24px' }}>
            <Card title="系统公告" extra={isAdmin && <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>发布公告</Button>}>
                <div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>
                    <Input 
                        placeholder="搜索公告标题或内容" 
                        style={{ width: 300 }} 
                        value={keyword}
                        onChange={e => setKeyword(e.target.value)}
                        onPressEnter={handleSearch}
                        allowClear
                    />
                    <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>搜索</Button>
                </div>

                <Table 
                    columns={columns} 
                    dataSource={data} 
                    rowKey="id" 
                    loading={loading}
                    pagination={{
                        ...pagination,
                        onChange: (page, pageSize) => setPagination({ ...pagination, current: page, pageSize })
                    }}
                />
            </Card>

            {/* 发布公告弹窗 */}
            <Modal
                title="发布新公告"
                open={isModalVisible}
                onOk={handleOk}
                onCancel={() => setIsModalVisible(false)}
                width={800}
                maskClosable={false}
            >
                <Form form={form} layout="vertical">
                    <Form.Item name="title" label="公告标题" rules={[{ required: true, message: '请输入标题' }]}>
                        <Input placeholder="请输入公告标题" />
                    </Form.Item>
                    <Form.Item name="content" label="公告内容" rules={[{ required: true, message: '请输入内容' }]}>
                        <MyEditor />
                    </Form.Item>
                    <Form.Item name="files" label="附件上传">
                        <Upload {...uploadProps} multiple>
                            <Button icon={<PaperClipOutlined />}>选择文件</Button>
                        </Upload>
                    </Form.Item>
                </Form>
            </Modal>

            {/* 公告详情弹窗 */}
            <Modal
                title={null}
                open={isDetailVisible}
                onCancel={() => setIsDetailVisible(false)}
                footer={[
                    <Button key="close" onClick={() => setIsDetailVisible(false)}>关闭</Button>
                ]}
                width={800}
            >
                {currentNotification && (
                    <div>
                        <div style={{ textAlign: 'center', marginBottom: 24, borderBottom: '1px solid #f0f0f0', paddingBottom: 16 }}>
                            <Title level={3}>{currentNotification.title}</Title>
                            <Space style={{ color: '#888' }}>
                                <span>发布人：{currentNotification.publisher_real_name || '管理员'}</span>
                                <span>发布时间：{new Date(currentNotification.created_at).toLocaleString()}</span>
                            </Space>
                        </div>
                        
                        <div 
                            className="wangeditor-content"
                            style={{ minHeight: 200, fontSize: '16px', lineHeight: '1.8' }}
                            dangerouslySetInnerHTML={{ __html: currentNotification.content }} 
                        />

                        {currentNotification.attachments && currentNotification.attachments.length > 0 && (
                            <div style={{ marginTop: 32, paddingTop: 16, borderTop: '1px dashed #d9d9d9' }}>
                                <Title level={5}><PaperClipOutlined /> 附件下载</Title>
                                <List
                                    size="small"
                                    dataSource={currentNotification.attachments}
                                    renderItem={item => (
                                        <List.Item>
                                            <Space>
                                                <FileTextOutlined />
                                                <Text>{item.file_name}</Text>
                                                <Button 
                                                    type="link" 
                                                    size="small" 
                                                    icon={<DownloadOutlined />} 
                                                    onClick={() => handleDownload(item)}
                                                >
                                                    下载
                                                </Button>
                                            </Space>
                                        </List.Item>
                                    )}
                                />
                            </div>
                        )}
                    </div>
                )}
            </Modal>
        </div>
    );
};

export default Notifications;
