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

const ContactsView = ({ friends, onRefresh, onStartChat }) => {
  const [isFriendModalVisible, setIsFriendModalVisible] = useState(false);
  const [isEditAliasModalVisible, setIsEditAliasModalVisible] = useState(false);
  const [editingFriend, setEditingFriend] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [addFriendForm] = Form.useForm();
  const [editAliasForm] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const handleAddFriend = async (values) => {
    setLoading(true);
    try {
      // 构造请求参数，如果有备注则添加
      const params = values.alias ? `?alias=${encodeURIComponent(values.alias)}` : '';
      await api.post(`/users/friends/${values.username}${params}`);
      message.success('好友添加成功');
      setIsFriendModalVisible(false);
      addFriendForm.resetFields();
      // 刷新好友列表
      if (onRefresh) {
        onRefresh();
      }
    } catch (e) {
      const errorMsg = e.response?.data?.detail || '添加好友失败';
      message.error(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const handleStartChat = async (friend) => {
    try {
      // 创建或获取与好友的私聊房间
      const res = await api.post(`/chatrooms/private/${friend.friend_id}`);
      message.success('正在进入私聊...');
      // 调用回调函数，切换到聊天视图
      if (onStartChat) {
        onStartChat(res.data);
      }
    } catch (e) {
      const errorMsg = e.response?.data?.detail || '创建私聊失败';
      message.error(errorMsg);
    }
  };

  const handleEditAlias = (friend) => {
    setEditingFriend(friend);
    editAliasForm.setFieldsValue({ alias: friend.alias || '' });
    setIsEditAliasModalVisible(true);
  };

  const handleUpdateAlias = async (values) => {
    setLoading(true);
    try {
      await api.put(`/users/friends/${editingFriend.friend_id}/alias`, null, {
        params: { alias: values.alias }
      });
      message.success('备注已更新');
      setIsEditAliasModalVisible(false);
      editAliasForm.resetFields();
      setEditingFriend(null);
      if (onRefresh) {
        onRefresh();
      }
    } catch (e) {
      message.error('更新失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteFriend = (friend) => {
    Modal.confirm({
      title: '确认删除好友',
      content: `确定要删除好友 ${friend.friend?.username} 吗？删除后将无法查看对方的动态。`,
      okText: '确定删除',
      cancelText: '取消',
      okButtonProps: { danger: true },
      onOk: async () => {
        try {
          await api.delete(`/users/friends/${friend.friend_id}`);
          message.success('好友已删除');
          if (onRefresh) {
            onRefresh();
          }
        } catch (e) {
          const errorMsg = e.response?.data?.detail || '删除失败';
          message.error(errorMsg);
        }
      }
    });
  };

  const getActionMenuItems = (friend) => [
    {
      key: 'chat',
      label: (
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="currentColor" strokeWidth="2"/>
          </svg>
          发送消息
        </div>
      ),
      onClick: () => handleStartChat(friend)
    },
    {
      key: 'edit',
      label: (
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" stroke="currentColor" strokeWidth="2"/>
            <path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="currentColor" strokeWidth="2"/>
          </svg>
          修改备注
        </div>
      ),
      onClick: () => handleEditAlias(friend)
    },
    {
      type: 'divider'
    },
    {
      key: 'delete',
      label: (
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px', color: '#ef4444' }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
            <polyline points="3 6 5 6 21 6" stroke="currentColor" strokeWidth="2"/>
            <path d="M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2" stroke="currentColor" strokeWidth="2"/>
          </svg>
          删除好友
        </div>
      ),
      onClick: () => handleDeleteFriend(friend),
      danger: true
    }
  ];

  const filtered = friends.filter(f =>
    f.friend?.username?.toLowerCase().includes(searchText.toLowerCase())
  );

  const recent = filtered.slice(0, 3);

  return (
    <div className="cv-root">
      {/* 顶部搜索 + 按钮 */}
      <div className="cv-topbar">
        <div className="cv-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="cv-search-input"
            placeholder="搜索联系人、备注、个性签名..."
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
          />
        </div>
        <button className="cv-add-btn" onClick={() => setIsFriendModalVisible(true)}>
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" aria-hidden="true">
            <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>
      </div>

      <div className="cv-body">
        <h2 className="cv-page-title">我的联系人</h2>
        <div className="cv-stats">
          <span className="cv-stat-tag cv-online">在线 {friends.filter(() => true).length}</span>
          <span className="cv-stat-tag">全部 {friends.length}</span>
        </div>

        {/* 最近联系 */}
        <section className="cv-section">
          <div className="cv-section-header">
            <button className="cv-collapse-btn">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M19 9l-7 7-7-7" stroke="#6b7280" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
            <span className="cv-section-title">最近联系（{recent.length}）</span>
          </div>

          <div className="cv-recent-grid">
            {/* AI 助手卡片 */}
            <div className="cv-recent-card cv-ai-card">
              <div className="cv-recent-card-inner">
                <div className="cv-recent-avatar cv-ai-avatar">
                  <svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </div>
                <div className="cv-recent-info">
                  <div className="cv-recent-name">灵犀 AI 助手</div>
                  <div className="cv-recent-bio">您的全能智能伙伴</div>
                </div>
                <button className="cv-msg-btn cv-msg-btn-white">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                </button>
              </div>
              <div className="cv-ai-footer">
                <span className="cv-ai-tag">SYSTEM AI</span>
                <span className="cv-ai-online">24/7 在线</span>
              </div>
            </div>

            {recent.map(f => (
              <div key={f.id} className="cv-recent-card">
                <div className="cv-recent-card-inner">
                  <div className="cv-recent-avatar">
                    {f.friend?.username?.[0]?.toUpperCase() || 'U'}
                    <span className="cv-online-dot" />
                  </div>
                  <div className="cv-recent-info">
                    <div className="cv-recent-name">{f.friend?.username}</div>
                    <div className="cv-recent-bio">{f.alias || '暂无签名'}</div>
                  </div>
                  <button className="cv-msg-btn" onClick={() => handleStartChat(f)}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                  </button>
                </div>
              </div>
            ))}
          </div>
        </section>

        {/* 我的好友 */}
        <section className="cv-section">
          <div className="cv-section-header">
            <button className="cv-collapse-btn">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M19 9l-7 7-7-7" stroke="#6b7280" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
            <span className="cv-section-title">我的好友（{filtered.length}）</span>
          </div>

          <div className="cv-friend-table">
            <div className="cv-table-header">
              <span>用户</span>
              <span>状态</span>
              <span>个性签名</span>
              <span>操作</span>
            </div>
            {filtered.length === 0 ? (
              <div className="cv-empty">暂无联系人，点击右上角添加好友</div>
            ) : (
              filtered.map(f => (
                <div key={f.id} className="cv-table-row">
                  <div className="cv-table-user">
                    <div className="cv-table-avatar">{f.friend?.username?.[0]?.toUpperCase() || 'U'}</div>
                    <div>
                      <div className="cv-table-name">{f.friend?.username}</div>
                      {f.alias && <div className="cv-table-alias">{f.alias}</div>}
                    </div>
                  </div>
                  <div className="cv-table-status">
                    <span className="cv-status-dot cv-status-online" />
                    <span className="cv-status-text">手机在线</span>
                  </div>
                  <div className="cv-table-bio">{f.alias || '暂无签名'}</div>
                  <div className="cv-table-actions">
                    <button className="cv-action-btn" onClick={() => handleStartChat(f)}>
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
                    </button>
                    <Dropdown
                      menu={{ items: getActionMenuItems(f) }}
                      trigger={['click']}
                      placement="bottomRight"
                    >
                      <button className="cv-action-btn">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></svg>
                      </button>
                    </Dropdown>
                  </div>
                </div>
              ))
            )}
            {filtered.length > 2 && (
              <div className="cv-load-more">
                <button className="cv-load-more-btn">加载更多联系人（{filtered.length - 2}）</button>
              </div>
            )}
          </div>
        </section>

        {/* 黑名单 */}
        <section className="cv-section">
          <div className="cv-section-header cv-collapsed">
            <button className="cv-collapse-btn">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M9 18l6-6-6-6" stroke="#6b7280" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></svg>
            </button>
            <span className="cv-section-title">黑名单（0）</span>
          </div>
        </section>
      </div>

      <Modal 
        title="添加好友" 
        open={isFriendModalVisible} 
        onCancel={() => {
          setIsFriendModalVisible(false);
          addFriendForm.resetFields();
        }} 
        footer={null}
      >
        <Form 
          form={addFriendForm}
          onFinish={handleAddFriend} 
          layout="vertical"
        >
          <Form.Item 
            name="username" 
            label="用户名" 
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input 
              placeholder="输入对方用户名" 
              prefix={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                  <path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" stroke="#9ca3af" strokeWidth="2"/>
                  <circle cx="12" cy="7" r="4" stroke="#9ca3af" strokeWidth="2"/>
                </svg>
              }
            />
          </Form.Item>
          <Form.Item 
            name="alias" 
            label="备注名称（可选）"
          >
            <Input 
              placeholder="给好友设置一个备注名" 
              prefix={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                  <path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" stroke="#9ca3af" strokeWidth="2"/>
                  <path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="#9ca3af" strokeWidth="2"/>
                </svg>
              }
            />
          </Form.Item>
          <Form.Item style={{ marginBottom: 0 }}>
            <Button type="primary" htmlType="submit" block loading={loading}>
              添加好友
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      {/* 修改备注 Modal */}
      <Modal
        title="修改备注"
        open={isEditAliasModalVisible}
        onCancel={() => {
          setIsEditAliasModalVisible(false);
          editAliasForm.resetFields();
          setEditingFriend(null);
        }}
        footer={null}
      >
        <Form
          form={editAliasForm}
          onFinish={handleUpdateAlias}
          layout="vertical"
        >
          <Form.Item
            name="alias"
            label="备注名称"
            rules={[{ required: true, message: '请输入备注名称' }]}
          >
            <Input
              placeholder="输入新的备注名称"
              prefix={
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
                  <path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7" stroke="#9ca3af" strokeWidth="2"/>
                  <path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z" stroke="#9ca3af" strokeWidth="2"/>
                </svg>
              }
            />
          </Form.Item>
          <Form.Item style={{ marginBottom: 0 }}>
            <Button type="primary" htmlType="submit" block loading={loading}>
              保存
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ContactsView;
