import React, { useState, useEffect } from 'react';
import { Card, Button, Table, Tag, Space, Modal, message, Progress } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, DownloadOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router';
import { useAuth } from '../hooks/AuthProvider';
import { solutionDesignsClient } from '@/client/api';

interface SolutionDesign {
  id: number;
  title: string;
  description: string | null;
  status: string;
  progress: number;
  totalChapters: number;
  completedChapters: number;
  outputFormat: string;
  createdAt: string;
  updatedAt: string;
}

const SolutionDesignsPage: React.FC = () => {
  const navigate = useNavigate();
  const { user } = useAuth();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<SolutionDesign[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const fetchSolutionDesigns = async (page: number = 1, pageSize: number = 10) => {
    try {
      setLoading(true);
      const response = await solutionDesignsClient.$get({
        query: {
          page,
          pageSize,
        },
      });

      if (response.status === 200) {
        const result = await response.json();
        setData(result.data);
        setPagination({
          current: result.pagination.current,
          pageSize: result.pagination.pageSize,
          total: result.pagination.total,
        });
      }
    } catch (error) {
      console.error('获取方案设计列表失败:', error);
      message.error('获取方案设计列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSolutionDesigns();
  }, []);

  const handleTableChange = (pagination: any) => {
    fetchSolutionDesigns(pagination.current, pagination.pageSize);
  };

  const handleCreate = () => {
    navigate('/admin/solution-designs/create');
  };

  const handleView = (id: number) => {
    navigate(`/admin/solution-designs/${id}`);
  };

  const handleEdit = (id: number) => {
    navigate(`/admin/solution-designs/${id}/edit`);
  };

  const handleDelete = async (id: number) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个方案设计吗？此操作不可恢复。',
      onOk: async () => {
        try {
          const response = await solutionDesignsClient[':id'].$delete({
            param: { id: id.toString() },
          });

          if (response.status === 200) {
            message.success('删除成功');
            fetchSolutionDesigns(pagination.current, pagination.pageSize);
          }
        } catch (error) {
          console.error('删除方案设计失败:', error);
          message.error('删除方案设计失败');
        }
      },
    });
  };

  const handleGenerate = async (id: number) => {
    try {
      const response = await solutionDesignsClient[':id'].generate.$post({
        param: { id: id.toString() },
      });

      if (response.status === 200) {
        const result = await response.json();
        message.success('文档生成成功');
        
        // 处理下载链接
        if (result.downloadUrl.startsWith('data:')) {
          // Base64数据，直接下载
          const link = document.createElement('a');
          link.href = result.downloadUrl;
          link.download = result.fileName;
          link.click();
        } else {
          // MinIO链接，新窗口打开
          window.open(result.downloadUrl, '_blank');
        }
      }
    } catch (error) {
      console.error('生成文档失败:', error);
      message.error('生成文档失败');
    }
  };

  const columns = [
    {
      title: '方案标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string, record: SolutionDesign) => (
        <Button type="link" onClick={() => handleView(record.id)}>
          {text}
        </Button>
      ),
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      render: (text: string | null) => text || '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => {
        const statusConfig = {
          draft: { color: 'default', text: '草稿' },
          reviewing: { color: 'processing', text: '审核中' },
          completed: { color: 'success', text: '已完成' },
        };
        const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '进度',
      dataIndex: 'progress',
      key: 'progress',
      render: (progress: number, record: SolutionDesign) => (
        <Progress 
          percent={progress} 
          size="small" 
          format={() => `${record.completedChapters}/${record.totalChapters}`}
        />
      ),
    },
    {
      title: '输出格式',
      dataIndex: 'outputFormat',
      key: 'outputFormat',
      render: (format: string) => <Tag>{format.toUpperCase()}</Tag>,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_: any, record: SolutionDesign) => (
        <Space size="middle">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            onClick={() => handleView(record.id)}
          >
            查看
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record.id)}
          >
            编辑
          </Button>
          {record.status === 'completed' && (
            <Button 
              type="link" 
              icon={<DownloadOutlined />} 
              onClick={() => handleGenerate(record.id)}
            >
              下载
            </Button>
          )}
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card
        title="方案设计管理"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            新建方案
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
        />
      </Card>
    </div>
  );
};

export default SolutionDesignsPage;