import React, { useEffect, useState } from "react";
import { Button } from "antd-mobile";
import { Select } from "antd";
import { AddOutline, UserAddOutline } from "antd-mobile-icons";
import CustomConditionModal from "./CustomConditionModal";
import FriendSearchModal from "./FriendSearchModal";
import ConditionList from "./ConditionList";
import styles from "./AudienceFilter.module.scss";
import {
  getIndustryOptions,
  getPresetSchemes,
  FilterField,
  PresetScheme,
} from "../api";

interface Friend {
  id: string;
  name: string;
  avatar: string;
  wechatId: string;
  tags: string[];
}

interface FilterCondition {
  id: string;
  type: string;
  label: string;
  value: any;
  operator?: string;
  field?: string;
  displayValue?: string;
  friends?: Friend[]; // 选中的好友列表
}

interface AudienceFilterProps {
  conditions: FilterCondition[];
  onChange: (conditions: FilterCondition[]) => void;
}

const AudienceFilter: React.FC<AudienceFilterProps> = ({
  conditions,
  onChange,
}) => {
  const [showCustomModal, setShowCustomModal] = useState(false);
  const [showFriendModal, setShowFriendModal] = useState(false);
  const [industryOptions, setIndustryOptions] = useState<FilterField[]>([]);
  const [presetSchemes, setPresetSchemes] = useState<PresetScheme[]>([]);
  const [selectedScheme, setSelectedScheme] = useState<string | undefined>(undefined);

  useEffect(() => {
    getIndustryOptions().then(res => setIndustryOptions(res || []));
    getPresetSchemes().then(res => setPresetSchemes(res || []));
  }, []);

  const handleSchemeChange = (schemeId: string) => {
    setSelectedScheme(schemeId);
    if (schemeId) {
      const scheme = presetSchemes.find(s => s.id === schemeId);
      if (scheme) {
        onChange(scheme.conditions);
      }
    } else {
      onChange([]);
    }
  };

  // 获取已选中的好友（从已有条件中提取）
  const getSelectedFriends = (): Friend[] => {
    const friendCondition = conditions.find(c => c.field === 'friendIds');
    return friendCondition?.friends || [];
  };

  // 处理好友选择确认
  const handleFriendsConfirm = (friends: Friend[]) => {
    // 移除旧的好友条件
    const newConditions = conditions.filter(c => c.field !== 'friendIds');

    if (friends.length > 0) {
      // 添加新的好友条件
      const friendCondition: FilterCondition = {
        id: 'friendIds',
        type: 'field',
        field: 'friendIds',
        label: '指定好友',
        operator: 'in',
        value: friends.map(f => f.id),
        displayValue: `已选 ${friends.length} 人`,
        friends: friends,
      };
      newConditions.push(friendCondition);
    }

    onChange(newConditions);
  };

  // 处理条件添加（排除好友搜索类型，因为有专门的按钮）
  const handleAddCondition = (condition: FilterCondition) => {
    // 如果是搜索好友条件，打开好友选择弹窗
    if (condition.field === 'keyword' && condition.fieldType === 'friend_search') {
      setShowFriendModal(true);
      return;
    }
    onChange([...conditions, condition]);
  };

  return (
    <div className={styles.container}>
      <div className={styles.section}>
        <div className={styles.sectionTitle}>人群方案</div>
        <div className={styles.selectWrapper}>
          <Select
            style={{ width: "100%" }}
            placeholder="选择预设方案"
            value={selectedScheme}
            onChange={handleSchemeChange}
            options={presetSchemes.map(scheme => ({
              label: `${scheme.name} (${scheme.userCount}人)`,
              value: scheme.id,
            }))}
            allowClear
          />
        </div>
      </div>

      <div className={styles.section}>
        <div className={styles.sectionTitle}>自定义条件</div>
        <ConditionList
          conditions={conditions}
          onRemove={(condition) => {
            const newConditions = conditions.filter(c =>
              c.field ? c.field !== condition.field : c.id !== condition.id
            );
            onChange(newConditions);
          }}
        />
        <div className={styles.buttonGroup}>
          <Button
            fill="none"
            className={styles.addBtn}
            onClick={() => setShowCustomModal(true)}
          >
            <AddOutline style={{ marginRight: 4 }} /> 添加筛选条件
          </Button>
          <Button
            fill="none"
            className={styles.friendBtn}
            onClick={() => setShowFriendModal(true)}
          >
            <UserAddOutline style={{ marginRight: 4 }} /> 选择好友
          </Button>
        </div>
      </div>

      <div className={styles.section}>
        <div className={styles.sectionTitle}>常用业务标签</div>
        <div className={styles.tagGrid}>
          {["高价值", "新客", "活跃", "待唤醒", "价格敏感", "忠诚"].map((tag, idx) => (
            <div key={idx} className={styles.tagItem}>{tag}</div>
          ))}
        </div>
      </div>

      <CustomConditionModal
        visible={showCustomModal}
        onClose={() => setShowCustomModal(false)}
        onAdd={handleAddCondition}
      />

      <FriendSearchModal
        visible={showFriendModal}
        onClose={() => setShowFriendModal(false)}
        onConfirm={handleFriendsConfirm}
        existingConditions={conditions.filter(c => c.field !== 'friendIds')}
        selectedFriends={getSelectedFriends()}
      />
    </div>
  );
};

export default AudienceFilter;
