import React, { useState, useEffect } from "react";
import {
  SearchOutlined,
  CloseOutlined,
  ArrowLeftOutlined,
  ArrowRightOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { Button, Input } from "antd";
import { Popup, Toast } from "antd-mobile";
import { getGroupList } from "./api";
import style from "./index.module.scss";

// 群组接口类型
interface WechatGroup {
  id: string;
  chatroomId: string;
  name: string;
  avatar: string;
  ownerWechatId: string;
  ownerNickname: string;
  ownerAvatar: string;
}

// 组件属性接口
interface GroupSelectionProps {
  selectedGroups: string[];
  onSelect: (groups: string[]) => void;
  onSelectDetail?: (groups: WechatGroup[]) => void;
  placeholder?: string;
  className?: string;
  visible?: boolean;
  onVisibleChange?: (visible: boolean) => void;
  selectedListMaxHeight?: number;
  showInput?: boolean;
  showSelectedList?: boolean;
  readonly?: boolean;
  onConfirm?: (selectedIds: string[], selectedItems: WechatGroup[]) => void; // 新增
}

export default function GroupSelection({
  selectedGroups,
  onSelect,
  onSelectDetail,
  placeholder = "选择群聊",
  className = "",
  visible,
  onVisibleChange,
  selectedListMaxHeight = 300,
  showInput = true,
  showSelectedList = true,
  readonly = false,
  onConfirm,
}: GroupSelectionProps) {
  const [popupVisible, setPopupVisible] = useState(false);
  const [groups, setGroups] = useState<WechatGroup[]>([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalGroups, setTotalGroups] = useState(0);
  const [loading, setLoading] = useState(false);

  // 获取已选群聊详细信息
  const selectedGroupObjs = selectedGroups
    .map((id) => groups.find((g) => g.id === id))
    .filter(Boolean) as WechatGroup[];

  // 删除已选群聊
  const handleRemoveGroup = (id: string) => {
    if (readonly) return;
    onSelect(selectedGroups.filter((g) => g !== id));
  };

  // 受控弹窗逻辑
  const realVisible = visible !== undefined ? visible : popupVisible;
  const setRealVisible = (v: boolean) => {
    if (onVisibleChange) onVisibleChange(v);
    if (visible === undefined) setPopupVisible(v);
  };

  // 打开弹窗
  const openPopup = () => {
    if (readonly) return;
    setCurrentPage(1);
    setSearchQuery("");
    setRealVisible(true);
    fetchGroups(1, "");
  };

  // 当页码变化时，拉取对应页数据（弹窗已打开时）
  useEffect(() => {
    if (realVisible && currentPage !== 1) {
      fetchGroups(currentPage, searchQuery);
    }
  }, [currentPage, realVisible, searchQuery]);

  // 搜索防抖
  useEffect(() => {
    if (!realVisible) return;
    const timer = setTimeout(() => {
      setCurrentPage(1);
      fetchGroups(1, searchQuery);
    }, 500);
    return () => clearTimeout(timer);
  }, [searchQuery, realVisible]);

  // 获取群组列表API - 支持keyword
  const fetchGroups = async (page: number, keyword: string = "") => {
    setLoading(true);
    try {
      const params: any = {
        page,
        limit: 20,
      };
      if (keyword.trim()) {
        params.keyword = keyword.trim();
      }

      const res = await getGroupList(params);

      if (res && Array.isArray(res.list)) {
        setGroups(
          res.list.map((group: any) => ({
            id: group.id?.toString() || "",
            chatroomId: group.chatroomId || "",
            name: group.name || "",
            avatar: group.avatar || "",
            ownerWechatId: group.ownerWechatId || "",
            ownerNickname: group.ownerNickname || "",
            ownerAvatar: group.ownerAvatar || "",
          }))
        );
        setTotalGroups(res.total || 0);
        setTotalPages(Math.ceil((res.total || 0) / 20));
      }
    } catch (error) {
      console.error("获取群组列表失败:", error);
      Toast.show({ content: "获取群组列表失败", position: "top" });
    } finally {
      setLoading(false);
    }
  };

  // 处理群组选择
  const handleGroupToggle = (groupId: string) => {
    let newIds: string[];
    if (selectedGroups.includes(groupId)) {
      newIds = selectedGroups.filter((id) => id !== groupId);
    } else {
      newIds = [...selectedGroups, groupId];
    }
    onSelect(newIds);
    if (onSelectDetail) {
      const selectedObjs = groups.filter((g) => newIds.includes(g.id));
      onSelectDetail(selectedObjs);
    }
  };

  // 获取显示文本
  const getDisplayText = () => {
    if (selectedGroups.length === 0) return "";
    return `已选择 ${selectedGroups.length} 个群聊`;
  };

  // 确认按钮逻辑
  const handleConfirm = () => {
    setRealVisible(false);
    if (onConfirm) {
      onConfirm(selectedGroups, selectedGroupObjs);
    }
  };

  // 清空搜索
  const handleClearSearch = () => {
    setSearchQuery("");
    setCurrentPage(1);
    fetchGroups(1, "");
  };

  return (
    <>
      {/* 输入框 */}
      {showInput && (
        <div className={`${style.inputWrapper} ${className}`}>
          <Input
            placeholder={placeholder}
            value={getDisplayText()}
            onClick={openPopup}
            prefix={<SearchOutlined />}
            allowClear={!readonly}
            size="large"
            readOnly={readonly}
            disabled={readonly}
            style={
              readonly ? { background: "#f5f5f5", cursor: "not-allowed" } : {}
            }
          />
        </div>
      )}
      {/* 已选群聊列表窗口 */}
      {showSelectedList && selectedGroupObjs.length > 0 && (
        <div
          className={style.selectedListWindow}
          style={{
            maxHeight: selectedListMaxHeight,
            overflowY: "auto",
            marginTop: 8,
            border: "1px solid #e5e6eb",
            borderRadius: 8,
            background: "#fff",
          }}
        >
          {selectedGroupObjs.map((group) => (
            <div
              key={group.id}
              className={style.selectedListRow}
              style={{
                display: "flex",
                alignItems: "center",
                padding: "4px 8px",
                borderBottom: "1px solid #f0f0f0",
                fontSize: 14,
              }}
            >
              <div
                style={{
                  flex: 1,
                  minWidth: 0,
                  whiteSpace: "nowrap",
                  overflow: "hidden",
                  textOverflow: "ellipsis",
                }}
              >
                {group.name || group.chatroomId || group.id}
              </div>
              {!readonly && (
                <Button
                  type="text"
                  icon={<DeleteOutlined />}
                  size="small"
                  style={{
                    marginLeft: 4,
                    color: "#ff4d4f",
                    border: "none",
                    background: "none",
                    minWidth: 24,
                    height: 24,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                  onClick={() => handleRemoveGroup(group.id)}
                />
              )}
            </div>
          ))}
        </div>
      )}
      {/* 弹窗 */}
      <Popup
        visible={realVisible && !readonly}
        onMaskClick={() => setRealVisible(false)}
        position="bottom"
        bodyStyle={{ height: "100vh" }}
      >
        <div className={style.popupContainer}>
          <div className={style.popupHeader}>
            <div className={style.popupTitle}>选择群聊</div>
            <div className={style.searchWrapper}>
              <Input
                placeholder="搜索群聊"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                disabled={readonly}
                prefix={<SearchOutlined />}
                allowClear
                size="large"
              />
              <SearchOutlined className={style.searchIcon} />
              {searchQuery && !readonly && (
                <Button
                  type="text"
                  icon={<CloseOutlined />}
                  size="small"
                  className={style.clearBtn}
                  onClick={handleClearSearch}
                  style={{
                    color: "#ff4d4f",
                    border: "none",
                    background: "none",
                    minWidth: 24,
                    height: 24,
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                />
              )}
            </div>
          </div>
          <div className={style.groupList}>
            {loading ? (
              <div className={style.loadingBox}>
                <div className={style.loadingText}>加载中...</div>
              </div>
            ) : groups.length > 0 ? (
              <div className={style.groupListInner}>
                {groups.map((group) => (
                  <label
                    key={group.id}
                    className={style.groupItem}
                    onClick={() => !readonly && handleGroupToggle(group.id)}
                  >
                    <div className={style.radioWrapper}>
                      <div
                        className={
                          selectedGroups.includes(group.id)
                            ? style.radioSelected
                            : style.radioUnselected
                        }
                      >
                        {selectedGroups.includes(group.id) && (
                          <div className={style.radioDot}></div>
                        )}
                      </div>
                    </div>
                    <div className={style.groupInfo}>
                      <div className={style.groupAvatar}>
                        {group.avatar ? (
                          <img
                            src={group.avatar}
                            alt={group.name}
                            className={style.avatarImg}
                          />
                        ) : (
                          group.name.charAt(0)
                        )}
                      </div>
                      <div className={style.groupDetail}>
                        <div className={style.groupName}>{group.name}</div>
                        <div className={style.groupId}>
                          群ID: {group.chatroomId}
                        </div>
                        {group.ownerNickname && (
                          <div className={style.groupOwner}>
                            群主: {group.ownerNickname}
                          </div>
                        )}
                      </div>
                    </div>
                  </label>
                ))}
              </div>
            ) : (
              <div className={style.emptyBox}>
                <div className={style.emptyText}>
                  {searchQuery
                    ? `没有找到包含"${searchQuery}"的群聊`
                    : "没有找到群聊"}
                </div>
              </div>
            )}
          </div>
          {/* 分页栏 */}
          <div className={style.paginationRow}>
            <div className={style.totalCount}>总计 {totalGroups} 个群聊</div>
            <div className={style.paginationControls}>
              <Button
                type="text"
                size="small"
                onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
                disabled={currentPage === 1 || loading}
                className={style.pageBtn}
                style={{ borderRadius: 16 }}
              >
                <ArrowLeftOutlined />
              </Button>
              <span className={style.pageInfo}>
                {currentPage} / {totalPages}
              </span>
              <Button
                type="text"
                size="small"
                onClick={() =>
                  setCurrentPage(Math.min(totalPages, currentPage + 1))
                }
                disabled={currentPage === totalPages || loading}
                className={style.pageBtn}
                style={{ borderRadius: 16 }}
              >
                <ArrowRightOutlined />
              </Button>
            </div>
          </div>
          {/* 底部按钮栏 */}
          <div className={style.popupFooter}>
            <div className={style.selectedCount}>
              已选择 {selectedGroups.length} 个群聊
            </div>
            <div className={style.footerBtnGroup}>
              <Button type="default" onClick={() => setRealVisible(false)}>
                取消
              </Button>
              <Button type="primary" onClick={handleConfirm}>
                确定
              </Button>
            </div>
          </div>
        </div>
      </Popup>
    </>
  );
}
