import React, { useState, useEffect } from 'react';
import { Card, Button, Input, Space, Tag, message, Popconfirm, Typography, Row, Col, List, Badge, Empty, Skeleton, Tooltip, Radio, Pagination } from 'antd';
import { 
  PlusOutlined, DeleteOutlined, SearchOutlined, CheckCircleOutlined, 
  LoadingOutlined, UserOutlined, CalendarOutlined, PlayCircleOutlined, 
  TeamOutlined, ClockCircleOutlined, EditOutlined, RightOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { getMeetingPage, deleteMeeting, MeetingVO, getMeetingProgress, MeetingProgress } from '../../api/business/meeting';
import dayjs from 'dayjs';
import { Progress } from 'antd';

const { Text, Title } = Typography;

// 进度显示组件
const MeetingProgressDisplay: React.FC<{ meeting: MeetingVO }> = ({ meeting }) => {
  const [progress, setProgress] = useState<MeetingProgress | null>(null);

  useEffect(() => {
    if (meeting.status !== 1 && meeting.status !== 2) return;
    const fetchProgress = async () => {
      try {
        const res = await getMeetingProgress(meeting.id);
        if (res.data && res.data.data) setProgress(res.data.data);
      } catch (err) {}
    };
    fetchProgress();
    const timer = setInterval(fetchProgress, 3000);
    return () => clearInterval(timer);
  }, [meeting.id, meeting.status]);

  if (meeting.status !== 1 && meeting.status !== 2) return null;

  const percent = progress?.percent || 0;
  const isError = percent < 0;

  return (
    <div style={{ padding: '0 24px 12px 24px', marginTop: -8 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
        <Text type="secondary" style={{ fontSize: 11 }}>
          {progress?.message || '处理中...'}
        </Text>
        {!isError && <Text strong style={{ color: '#1890ff', fontSize: 11 }}>{percent}%</Text>}
      </div>
      <Progress 
        percent={isError ? 100 : percent} 
        size="small" 
        status={isError ? 'exception' : 'active'}
        showInfo={false}
        strokeColor={isError ? '#ff4d4f' : '#1890ff'}
        style={{ margin: 0 }}
      />
    </div>
  );
};

const Meetings: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<MeetingVO[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [size, setSize] = useState(8);
  const [searchTitle, setSearchTitle] = useState('');
  const [viewType, setViewType] = useState<'all' | 'created' | 'involved'>('all');

  useEffect(() => {
    fetchData();
  }, [current, size, searchTitle, viewType]);

  const fetchData = async () => {
    setLoading(true);
    try {
      const res = await getMeetingPage({ current, size, title: searchTitle, viewType });
      if (res.data && res.data.data) {
        setData(res.data.data.records);
        setTotal(res.data.data.total);
      }
    } catch (err) {
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const statusConfig: Record<number, { text: string; color: string; bgColor: string }> = {
    0: { text: '排队中', color: '#8c8c8c', bgColor: '#f5f5f5' },
    1: { text: '识别中', color: '#1890ff', bgColor: '#e6f7ff' },
    2: { text: '总结中', color: '#faad14', bgColor: '#fff7e6' },
    3: { text: '已完成', color: '#52c41a', bgColor: '#f6ffed' },
    4: { text: '失败', color: '#ff4d4f', bgColor: '#fff1f0' }
  };

  return (
    <div style={{ 
      height: 'calc(100vh - 64px)', 
      display: 'flex', 
      flexDirection: 'column',
      backgroundColor: '#f4f7f9', 
      padding: '24px',
      overflow: 'hidden' 
    }}>
      <div style={{ maxWidth: 1600, margin: '0 auto', width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
        
        {/* 固定头部 - 极简白卡 */}
        <Card bordered={false} style={{ marginBottom: 20, borderRadius: 16, flexShrink: 0, boxShadow: '0 4px 12px rgba(0,0,0,0.03)' }} bodyStyle={{ padding: '16px 28px' }}>
          <Row justify="space-between" align="middle">
            <Col>
              <Space size={12}>
                <div style={{ width: 8, height: 24, background: '#1890ff', borderRadius: 4 }}></div>
                <Title level={4} style={{ margin: 0 }}>会议中心</Title>
              </Space>
            </Col>
            <Col>
              <Space size={16}>
                <Radio.Group value={viewType} onChange={e => { setViewType(e.target.value); setCurrent(1); }} buttonStyle="solid">
                  <Radio.Button value="all">全部</Radio.Button>
                  <Radio.Button value="created">我发起</Radio.Button>
                  <Radio.Button value="involved">我参与</Radio.Button>
                </Radio.Group>
                <Input 
                  placeholder="搜索会议标题" 
                  prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />} 
                  allowClear 
                  onPressEnter={(e) => { setSearchTitle((e.target as any).value); setCurrent(1); }} 
                  style={{ width: 220, borderRadius: 8 }} 
                />
                <Button 
                  type="primary" 
                  icon={<PlusOutlined />} 
                  onClick={() => navigate('/meeting-create')}
                  style={{ borderRadius: 8, height: 36, fontWeight: 500 }}
                >
                  新会议
                </Button>
              </Space>
            </Col>
          </Row>
        </Card>

        {/* 列表区 */}
        <div style={{ flex: 1, overflowY: 'auto', overflowX: 'hidden', padding: '4px 8px 4px 4px' }}>
          <Skeleton loading={loading} active paragraph={{ rows: 10 }}>
            <List
              grid={{ gutter: 24, xs: 1, sm: 2, md: 2, lg: 3, xl: 4, xxl: 4 }}
              dataSource={data}
              renderItem={(item) => {
                const config = statusConfig[item.status] || statusConfig[0];
                return (
                  <List.Item style={{ marginBottom: 24 }}>
                    <Card 
                      hoverable
                      onClick={() => navigate(`/meetings/${item.id}`)}
                      className="meeting-card"
                      style={{ 
                        borderRadius: 16, 
                        border: 'none', 
                        height: 'auto', 
                        minHeight: '220px',
                        position: 'relative',
                        boxShadow: '0 6px 16px rgba(0,0,0,0.04)',
                        transition: 'all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1)'
                      }}
                      bodyStyle={{ padding: 0, display: 'flex', flexDirection: 'column' }}
                    >
                      <div style={{ display: 'flex', flex: 1 }}>
                        {/* 左侧状态装饰条 */}
                        <div style={{ width: 6, backgroundColor: config.color, borderRadius: '16px 0 0 16px' }}></div>
                        
                        <div style={{ flex: 1, padding: '20px 24px', position: 'relative', display: 'flex', flexDirection: 'column' }}>
                          
                          {/* 右上角醒目图标 */}
                          <div className="card-actions" style={{ position: 'absolute', top: 16, right: 16, zIndex: 10 }} onClick={e => e.stopPropagation()}>
                            <Space size={8}>
                              <Tooltip title="编辑">
                                <div className="icon-btn edit" onClick={() => navigate(`/meetings/${item.id}`)}>
                                  <EditOutlined />
                                </div>
                              </Tooltip>
                              <Popconfirm title="确定删除？" onConfirm={() => deleteMeeting(item.id).then(fetchData)}>
                                <Tooltip title="删除">
                                  <div className="icon-btn delete">
                                    <DeleteOutlined />
                                  </div>
                                </Tooltip>
                              </Popconfirm>
                            </Space>
                          </div>

                          {/* 内容排版 */}
                          <div style={{ flex: 1 }}>
                            <div style={{ marginBottom: 12 }}>
                              <Tag color={config.bgColor} style={{ color: config.color, border: 'none', borderRadius: 4, fontWeight: 600, fontSize: 11 }}>
                                {item.status === 1 || item.status === 2 ? <LoadingOutlined spin style={{ marginRight: 4 }} /> : null}
                                {config.text}
                              </Tag>
                            </div>

                            <div style={{ marginBottom: 16, paddingRight: 40, height: '44px', overflow: 'hidden' }}>
                              <Text strong style={{ fontSize: 16, color: '#262626', lineHeight: '22px' }} ellipsis={{ tooltip: item.title }}>
                                {item.title}
                              </Text>
                            </div>

                            <Space direction="vertical" size={10} style={{ width: '100%' }}>
                              <div style={{ fontSize: '13px', color: '#8c8c8c', display: 'flex', alignItems: 'center' }}>
                                <CalendarOutlined style={{ marginRight: 10 }} />
                                {dayjs(item.meetingTime).format('YYYY-MM-DD HH:mm')}
                              </div>
                              <div style={{ fontSize: '13px', color: '#8c8c8c', display: 'flex', alignItems: 'center' }}>
                                <TeamOutlined style={{ marginRight: 10 }} />
                                <Text type="secondary" ellipsis style={{ maxWidth: '85%' }}>{item.participants || '无参与人员'}</Text>
                              </div>
                            </Space>
                          </div>

                          {/* 底部详情提示 */}
                          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 12 }}>
                            <div style={{ display: 'flex', gap: 4 }}>
                              {item.tags?.split(',').slice(0, 2).map(t => (
                                <Tag key={t} style={{ border: '1px solid #f0f0f0', backgroundColor: '#fff', fontSize: 10, margin: 0, borderRadius: 4 }}>{t}</Tag>
                              ))}
                            </div>
                            <RightOutlined style={{ color: '#bfbfbf', fontSize: 12 }} />
                          </div>
                        </div>
                      </div>
                      
                      {/* 进度条显示 */}
                      <MeetingProgressDisplay meeting={item} />
                    </Card>
                  </List.Item>
                );
              }}
              locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="开启您的第一场会议分析" /> }}
            />
          </Skeleton>
        </div>

        {/* 精美底部分页 */}
        {total > 0 && (
          <div style={{ flexShrink: 0, display: 'flex', justifyContent: 'center', padding: '16px 0 8px 0' }}>
            <Pagination
              current={current}
              pageSize={size}
              total={total}
              onChange={(p, s) => { setCurrent(p); setSize(s); }}
              showTotal={(total) => <Text type="secondary" size="small">为您找到 {total} 场会议</Text>}
              size="small"
            />
          </div>
        )}
      </div>
      <style>{`
        .meeting-card:hover {
          transform: translateY(-4px);
          box-shadow: 0 12px 24px rgba(0,0,0,0.08) !important;
        }
        .icon-btn {
          width: 32px;
          height: 32px;
          border-radius: 50%;
          background: rgba(255,255,255,0.9);
          display: flex;
          justify-content: center;
          align-items: center;
          box-shadow: 0 2px 6px rgba(0,0,0,0.1);
          transition: all 0.2s;
          color: #8c8c8c;
        }
        .icon-btn:hover {
          transform: scale(1.1);
        }
        .icon-btn.edit:hover {
          color: #1890ff;
          background: #e6f7ff;
        }
        .icon-btn.delete:hover {
          color: #ff4d4f;
          background: #fff1f0;
        }
        .card-actions {
          opacity: 0.6;
          transition: opacity 0.3s;
        }
        .meeting-card:hover .card-actions {
          opacity: 1;
        }
      `}</style>
    </div>
  );
};

export default Meetings;
