
import { UserAddOutlined, UserDeleteOutlined } from '@ant-design/icons';
import { useRequest } from '@umijs/max';
import { Avatar, Input, List, Button, Space, Popconfirm, message, Modal, Tooltip } from 'antd';
import type { FC } from 'react';
import { useState } from 'react';
import { addFriend, queryCurrent, queryFriendList, searchUsername } from '../../service';
import type { FriendUser, UserInfo } from '../../data';
type Friend = { id: string; name: string; avatar?: string; remark?: string };
const ListContent = ({
  data: { nickname, remark, createFriendTime, friendStatus },
}: {
  data: FriendUser;
}) => {
  return (
    <div >
      <div>
        <span>昵称：{nickname}</span>
        <span>备注：{remark}</span>
        <span>创建时间：{createFriendTime}</span>
        <span>好友状态：{friendStatus}</span>
      </div>
    </div>
  );
};


// 好友 Tab：展示并管理好友（前端状态占位实现）
const Friends: FC = () => {

  const [searchUsers, setSearchUsers] = useState<UserInfo[]>([]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [friends, setFriends] = useState<FriendUser[]>([]);


  const {run} = useRequest(() => queryFriendList(), {
    onSuccess: (data) => {
      setFriends(data ?? []);
    },
    onError: (error) => {
      message.error(error.message);
    }
  })
  
  const handleSearch = async (v: string) => {
    console.log(v);
    const res = await searchUsername({username: v});
    setSearchUsers(res.data);
    
  }

  const handleSelectFriend = async (candidate: UserInfo) => {
    if (friends?.some((f) => f.userId === candidate.userId)) {
      message.info('该好友已存在');
      return;
    }
    console.log(candidate);
    const res = await addFriend(candidate.userId);
    console.log(res);
    if (res.code === 200) {
      message.success(res.message);
      run();
    }
    
  };

  const handleRemove = (id: string) => {

    message.success('已移除好友（本地状态）');
  };

  return (
    <div>
      <Space style={{ marginBottom: 16 }}>
        <Button
          type="primary"
          icon={<UserAddOutlined />}
          onClick={() => {
            setSearchKeyword('');
            setAddModalVisible(true);
          }}
        >
          添加好友
        </Button>
      </Space>
      <List
        itemLayout="horizontal"
        dataSource={friends}
        locale={{ emptyText: '暂无好友' }}
        renderItem={(item) => (
          <List.Item
            actions={[
              <Popconfirm
                key="remove"
                title="确定删除该好友？"
                onConfirm={() => handleRemove(item.userId)}
              >
                <Button type="link" icon={<UserDeleteOutlined />}>删除</Button>
              </Popconfirm>,
            ]}
          >
            <List.Item.Meta
              avatar={<Avatar src={item.avatar}>{item.username}</Avatar>}
              title={item.username}
              description={item.description}
            />
            <ListContent data={item} />
          </List.Item>
        )}
      />

      <Modal
        title="添加好友"
        open={addModalVisible}
        onCancel={() => setAddModalVisible(false)}
        footer={null}
        destroyOnClose
      >
        <Input.Search
          placeholder="搜索好友名称"
          allowClear
          onSearch={handleSearch}
          onChange={(e) => setSearchKeyword(e.target.value.trim())}
          style={{ marginBottom: 16 }}
        />
        <List
          locale={{ emptyText: '未找到匹配的用户' }}
          dataSource={searchUsers}
          renderItem={(item) => (
            <List.Item
              actions={[
                <Button key="add" type="link" onClick={() => handleSelectFriend(item)}>
                  添加
                </Button>,
              ]}
            >
              <List.Item.Meta
                avatar={<Avatar src={item.avatar}>{item.username}</Avatar>}
                title={item.username}
                description={item.description}
              />
            </List.Item>
          )}
        />
      </Modal>
    </div>
  );
};

export default Friends;