import React, { useState } from 'react';
import { Modal, Form, Input, Button, message, Checkbox, Transfer } from 'antd';
import api from '../services/api';
import './GroupsView.css';

const GroupsView = ({ chatRooms, friends, onRefresh, onEnterRoom }) => {
  const [isCreateVisible, setIsCreateVisible] = useState(false);
  const [isAddMemberVisible, setIsAddMemberVisible] = useState(false);
  const [selectedRoom, setSelectedRoom] = useState(null);
  const [selectedMembers, setSelectedMembers] = useState([]);
  const [selectedEmployees, setSelectedEmployees] = useState([]);
  const [searchText, setSearchText] = useState('');
  const [createForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [digitalEmployees, setDigitalEmployees] = useState([]);

  const handleCreate = async (values) => {
    setLoading(true);
    try {
      // 创建群组，并添加选中的成员
      const response = await api.post('/chatrooms/', { 
        name: values.name,
        member_ids: selectedMembers 
      });
      
      const roomId = response.data.id;
      
      // 添加数字员工（如果有）
      for (const employeeId of selectedEmployees) {
        try {
          await api.post(`/chatrooms/${roomId}/add_employee/${employeeId}`);
        } catch (e) {
          console.error(`添加数字员工 ${employeeId} 失败:`, e);
        }
      }
      
      message.success('聊天室创建成功');
      setIsCreateVisible(false);
      createForm.resetFields();
      setSelectedMembers([]);
      setSelectedEmployees([]);
      if (onRefresh) {
        onRefresh();
      }
    } catch (e) {
      const errorMsg = e.response?.data?.detail || '创建失败';
      message.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const handleAddMember = async (values) => {
    if (!selectedRoom || (selectedMembers.length === 0 && selectedEmployees.length === 0)) {
      message.warning('请选择要添加的成员或数字员工');
      return;
    }
    
    setLoading(true);
    try {
      // 逐个添加成员
      for (const memberId of selectedMembers) {
        await api.post(`/chatrooms/${selectedRoom.id}/add_user/${memberId}`);
      }
      
      // 添加数字员工（如果有）
      for (const employeeId of selectedEmployees) {
        // 这里可以调用专门的 API 添加数字员工
        // 暂时使用相同的接口，后端需要支持
        await api.post(`/chatrooms/${selectedRoom.id}/add_employee/${employeeId}`);
      }
      
      const totalAdded = selectedMembers.length + selectedEmployees.length;
      message.success(`成功添加 ${totalAdded} 个成员`);
      setIsAddMemberVisible(false);
      setSelectedMembers([]);
      setSelectedEmployees([]);
      setSelectedRoom(null);
    } catch (e) {
      const errorMsg = e.response?.data?.detail || '添加成员失败';
      message.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  // 获取数字员工列表
  const fetchDigitalEmployees = async () => {
    try {
      const res = await api.get('/ai-agents/employees/public');
      setDigitalEmployees(res.data);
    } catch (e) {
      console.error('获取数字员工列表失败:', e);
    }
  };

  // 组件加载时获取数字员工列表
  React.useEffect(() => {
    fetchDigitalEmployees();
  }, []);

  const handleCopyLink = (room) => {
    const link = `${window.location.origin}/join/${room.share_link}`;
    navigator.clipboard.writeText(link);
    message.success('分享链接已复制到剪贴板');
  };

  const handleLeaveRoom = (room) => {
    Modal.confirm({
      title: '确认退出群组',
      content: `确定要退出"${room.name}"吗？退出后将无法接收群消息。`,
      okText: '确定退出',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await api.post(`/chatrooms/${room.id}/leave`);
          message.success('已退出群组');
          if (onRefresh) {
            onRefresh();
          }
        } catch (e) {
          const errorMsg = e.response?.data?.detail || '退出失败';
          message.error(errorMsg);
        }
      }
    });
  };

  const openAddMemberModal = (room) => {
    setSelectedRoom(room);
    setSelectedMembers([]);
    setSelectedEmployees([]);
    setIsAddMemberVisible(true);
  };

  const filtered = chatRooms.filter(r =>
    r.name?.toLowerCase().includes(searchText.toLowerCase())
  );

  const colors = [
    'linear-gradient(135deg,#4f46e5,#7c3aed)',
    'linear-gradient(135deg,#0ea5e9,#6366f1)',
    'linear-gradient(135deg,#f59e0b,#ef4444)',
    'linear-gradient(135deg,#10b981,#06b6d4)',
  ];

  return (
    <div className="gv-root">
      {/* 顶部搜索 */}
      <div className="gv-topbar">
        <div className="gv-search-wrap">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" aria-hidden="true">
            <circle cx="11" cy="11" r="8" stroke="#9ca3af" strokeWidth="2"/>
            <path d="M21 21l-4.35-4.35" stroke="#9ca3af" strokeWidth="2" strokeLinecap="round"/>
          </svg>
          <input
            className="gv-search-input"
            placeholder="搜索群聊或消息..."
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
          />
        </div>
      </div>

      <div className="gv-body">
        <div className="gv-page-header">
          <div>
            <h2 className="gv-page-title">我的群组</h2>
            <p className="gv-page-sub">管理您的 AI 协作室与技术社区</p>
          </div>
          <button className="gv-create-btn" onClick={() => setIsCreateVisible(true)}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" aria-hidden="true">
              <line x1="12" y1="5" x2="12" y2="19" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
              <line x1="5" y1="12" x2="19" y2="12" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/>
            </svg>
            创建聊天室
          </button>
        </div>

        <div className="gv-grid">
          {filtered.map((room, i) => (
            <div key={room.id} className="gv-card">
              <div className="gv-card-header">
                <div className="gv-room-avatar" style={{ background: colors[i % colors.length] }}>
                  {room.name?.[0]?.toUpperCase() || 'G'}
                  <span className="gv-online-dot" />
                </div>
                <div className="gv-room-meta">
                  <div className="gv-room-name">{room.name}</div>
                  <div className="gv-room-info">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke="#9ca3af" strokeWidth="2" strokeLinecap="round"/><circle cx="9" cy="7" r="4" stroke="#9ca3af" strokeWidth="2"/></svg>
                    <span>活跃中</span>
                  </div>
                </div>
                <div className="gv-card-actions">
                  <button className="gv-icon-btn" title="添加成员" onClick={() => openAddMemberModal(room)}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M16 21v-2a4 4 0 00-4-4H6a4 4 0 00-4 4v2" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><circle cx="9" cy="7" r="4" stroke="currentColor" strokeWidth="2"/><line x1="19" y1="8" x2="19" y2="14" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/><line x1="22" y1="11" x2="16" y2="11" stroke="currentColor" strokeWidth="2" strokeLinecap="round"/></svg>
                  </button>
                  <button className="gv-icon-btn" title="复制链接" onClick={() => handleCopyLink(room)}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/><path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </button>
                  <button 
                    className="gv-icon-btn" 
                    title="退出群组"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleLeaveRoom(room);
                    }}
                  >
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4M16 17l5-5-5-5M21 12H9" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </button>
                </div>
              </div>

              <div className="gv-latest-msg">
                <span className="gv-latest-tag">最新消息</span>
                <span className="gv-latest-time">刚刚</span>
              </div>
              <div className="gv-latest-content">点击进入群聊，开始协作...</div>

              <div className="gv-card-footer">
                <div className="gv-member-avatars">
                  {[0,1,2].map(j => (
                    <div key={j} className="gv-member-dot" style={{ background: colors[(i + j) % colors.length], marginLeft: j > 0 ? '-6px' : 0 }} />
                  ))}
                </div>
                <button className="gv-enter-btn" onClick={() => onEnterRoom?.(room)}>
                  进入群聊
                </button>
              </div>
            </div>
          ))}

          {/* 探索更多 */}
          <div className="gv-card gv-explore-card">
            <div className="gv-explore-icon">
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none"><circle cx="11" cy="11" r="8" stroke="#d1d5db" strokeWidth="2"/><path d="M21 21l-4.35-4.35" stroke="#d1d5db" strokeWidth="2" strokeLinecap="round"/></svg>
            </div>
            <div className="gv-explore-title">探索更多公开群组</div>
            <div className="gv-explore-sub">发现与您志趣相投的专业社区</div>
            <button className="gv-explore-link">去发现频道看看</button>
          </div>
        </div>
      </div>

      {/* 创建聊天室 */}
      <Modal 
        title="创建聊天室" 
        open={isCreateVisible} 
        onCancel={() => {
          setIsCreateVisible(false);
          createForm.resetFields();
          setSelectedMembers([]);
          setSelectedEmployees([]);
        }} 
        footer={null}
        width={600}
      >
        <Form 
          form={createForm}
          onFinish={handleCreate} 
          layout="vertical"
        >
          <Form.Item 
            name="name" 
            label="聊天室名称" 
            rules={[{ required: true, message: '请输入名称' }]}
          >
            <Input placeholder="输入聊天室名称" />
          </Form.Item>
          
          <Form.Item label="邀请好友（可选）">
            <div className="gv-member-select">
              {friends && friends.length > 0 ? (
                friends.map(f => (
                  <div key={f.friend_id} className="gv-member-item">
                    <Checkbox
                      checked={selectedMembers.includes(f.friend_id)}
                      onChange={(e) => {
                        if (e.target.checked) {
                          setSelectedMembers([...selectedMembers, f.friend_id]);
                        } else {
                          setSelectedMembers(selectedMembers.filter(id => id !== f.friend_id));
                        }
                      }}
                    >
                      <div className="gv-member-info">
                        <div className="gv-member-avatar-small">
                          {f.friend?.username?.[0]?.toUpperCase() || 'U'}
                        </div>
                        <span>{f.friend?.username}</span>
                        {f.alias && <span className="gv-member-alias">({f.alias})</span>}
                      </div>
                    </Checkbox>
                  </div>
                ))
              ) : (
                <div className="gv-empty-friends">暂无好友，请先添加好友</div>
              )}
            </div>
            {selectedMembers.length > 0 && (
              <div className="gv-selected-count">已选择 {selectedMembers.length} 个好友</div>
            )}
          </Form.Item>

          <Form.Item label="添加数字员工（可选）">
            <div className="gv-member-select">
              {digitalEmployees && digitalEmployees.length > 0 ? (
                digitalEmployees.map(emp => (
                  <div key={emp.id} className="gv-member-item">
                    <Checkbox
                      checked={selectedEmployees.includes(emp.id)}
                      onChange={(e) => {
                        if (e.target.checked) {
                          setSelectedEmployees([...selectedEmployees, emp.id]);
                        } else {
                          setSelectedEmployees(selectedEmployees.filter(id => id !== emp.id));
                        }
                      }}
                    >
                      <div className="gv-member-info">
                        <div className="gv-member-avatar-small gv-employee-avatar">
                          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                            <circle cx="12" cy="12" r="3" stroke="white" strokeWidth="2"/>
                            <path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="white" strokeWidth="2" strokeLinecap="round"/>
                          </svg>
                        </div>
                        <span>{emp.name}</span>
                        <span className="gv-employee-badge">AI</span>
                      </div>
                    </Checkbox>
                  </div>
                ))
              ) : (
                <div className="gv-empty-friends">暂无数字员工可添加</div>
              )}
            </div>
            {selectedEmployees.length > 0 && (
              <div className="gv-selected-count">已选择 {selectedEmployees.length} 个数字员工</div>
            )}
          </Form.Item>
          
          <Form.Item style={{ marginBottom: 0 }}>
            <Button type="primary" htmlType="submit" block loading={loading}>
              创建聊天室
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加成员 */}
      <Modal
        title={`添加成员到 "${selectedRoom?.name}"`}
        open={isAddMemberVisible}
        onCancel={() => {
          setIsAddMemberVisible(false);
          setSelectedMembers([]);
          setSelectedEmployees([]);
          setSelectedRoom(null);
        }}
        footer={null}
        width={600}
      >
        <div className="gv-add-member-content">
          {/* 好友列表 */}
          <div className="gv-section-title">选择好友</div>
          <div className="gv-member-select">
            {friends && friends.length > 0 ? (
              friends.map(f => (
                <div key={f.friend_id} className="gv-member-item">
                  <Checkbox
                    checked={selectedMembers.includes(f.friend_id)}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setSelectedMembers([...selectedMembers, f.friend_id]);
                      } else {
                        setSelectedMembers(selectedMembers.filter(id => id !== f.friend_id));
                      }
                    }}
                  >
                    <div className="gv-member-info">
                      <div className="gv-member-avatar-small">
                        {f.friend?.username?.[0]?.toUpperCase() || 'U'}
                      </div>
                      <span>{f.friend?.username}</span>
                      {f.alias && <span className="gv-member-alias">({f.alias})</span>}
                    </div>
                  </Checkbox>
                </div>
              ))
            ) : (
              <div className="gv-empty-friends">暂无好友可添加</div>
            )}
          </div>
          {selectedMembers.length > 0 && (
            <div className="gv-selected-count">已选择 {selectedMembers.length} 个好友</div>
          )}

          {/* 数字员工列表 */}
          <div className="gv-section-title" style={{ marginTop: 24 }}>选择数字员工</div>
          <div className="gv-member-select">
            {digitalEmployees && digitalEmployees.length > 0 ? (
              digitalEmployees.map(emp => (
                <div key={emp.id} className="gv-member-item">
                  <Checkbox
                    checked={selectedEmployees.includes(emp.id)}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setSelectedEmployees([...selectedEmployees, emp.id]);
                      } else {
                        setSelectedEmployees(selectedEmployees.filter(id => id !== emp.id));
                      }
                    }}
                  >
                    <div className="gv-member-info">
                      <div className="gv-member-avatar-small gv-employee-avatar">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                          <circle cx="12" cy="12" r="3" stroke="white" strokeWidth="2"/>
                          <path d="M19.07 4.93l-1.41 1.41M5.34 18.66l-1.41 1.41M20 12h-2M6 12H4M19.07 19.07l-1.41-1.41M5.34 5.34L3.93 3.93M12 20v-2M12 6V4" stroke="white" strokeWidth="2" strokeLinecap="round"/>
                        </svg>
                      </div>
                      <span>{emp.name}</span>
                      <span className="gv-employee-badge">AI</span>
                    </div>
                  </Checkbox>
                </div>
              ))
            ) : (
              <div className="gv-empty-friends">暂无数字员工可添加</div>
            )}
          </div>
          {selectedEmployees.length > 0 && (
            <div className="gv-selected-count">已选择 {selectedEmployees.length} 个数字员工</div>
          )}

          <Button 
            type="primary" 
            block 
            loading={loading}
            onClick={handleAddMember}
            disabled={selectedMembers.length === 0 && selectedEmployees.length === 0}
            style={{ marginTop: 16 }}
          >
            添加成员 ({selectedMembers.length + selectedEmployees.length})
          </Button>
        </div>
      </Modal>
    </div>
  );
};

export default GroupsView;
