import React, { useEffect, useState } from "react";
import { Popup, Button, Input, Selector, List } from "antd-mobile";
import styles from "./CustomConditionModal.module.scss";
import { getIndustryOptions, FilterField } from "../api";

// 省市数据
const areaData = [
  { label: '北京', value: '110000', children: [{ label: '北京市', value: '110100' }] },
  { label: '天津', value: '120000', children: [{ label: '天津市', value: '120100' }] },
  { label: '河北', value: '130000', children: [
    { label: '石家庄市', value: '130100' }, { label: '唐山市', value: '130200' },
    { label: '秦皇岛市', value: '130300' }, { label: '邯郸市', value: '130400' },
    { label: '邢台市', value: '130500' }, { label: '保定市', value: '130600' },
    { label: '张家口市', value: '130700' }, { label: '承德市', value: '130800' },
    { label: '沧州市', value: '130900' }, { label: '廊坊市', value: '131000' },
  ]},
  { label: '山西', value: '140000', children: [
    { label: '太原市', value: '140100' }, { label: '大同市', value: '140200' },
    { label: '阳泉市', value: '140300' }, { label: '长治市', value: '140400' },
    { label: '晋城市', value: '140500' }, { label: '朔州市', value: '140600' },
  ]},
  { label: '内蒙古', value: '150000', children: [
    { label: '呼和浩特市', value: '150100' }, { label: '包头市', value: '150200' },
    { label: '乌海市', value: '150300' }, { label: '赤峰市', value: '150400' },
  ]},
  { label: '辽宁', value: '210000', children: [
    { label: '沈阳市', value: '210100' }, { label: '大连市', value: '210200' },
    { label: '鞍山市', value: '210300' }, { label: '抚顺市', value: '210400' },
  ]},
  { label: '吉林', value: '220000', children: [
    { label: '长春市', value: '220100' }, { label: '吉林市', value: '220200' },
    { label: '四平市', value: '220300' }, { label: '辽源市', value: '220400' },
  ]},
  { label: '黑龙江', value: '230000', children: [
    { label: '哈尔滨市', value: '230100' }, { label: '齐齐哈尔市', value: '230200' },
    { label: '鸡西市', value: '230300' }, { label: '鹤岗市', value: '230400' },
  ]},
  { label: '上海', value: '310000', children: [{ label: '上海市', value: '310100' }] },
  { label: '江苏', value: '320000', children: [
    { label: '南京市', value: '320100' }, { label: '无锡市', value: '320200' },
    { label: '徐州市', value: '320300' }, { label: '常州市', value: '320400' },
    { label: '苏州市', value: '320500' }, { label: '南通市', value: '320600' },
  ]},
  { label: '浙江', value: '330000', children: [
    { label: '杭州市', value: '330100' }, { label: '宁波市', value: '330200' },
    { label: '温州市', value: '330300' }, { label: '嘉兴市', value: '330400' },
    { label: '湖州市', value: '330500' }, { label: '绍兴市', value: '330600' },
  ]},
  { label: '安徽', value: '340000', children: [
    { label: '合肥市', value: '340100' }, { label: '芜湖市', value: '340200' },
    { label: '蚌埠市', value: '340300' }, { label: '淮南市', value: '340400' },
  ]},
  { label: '福建', value: '350000', children: [
    { label: '福州市', value: '350100' }, { label: '厦门市', value: '350200' },
    { label: '莆田市', value: '350300' }, { label: '三明市', value: '350400' },
    { label: '泉州市', value: '350500' }, { label: '漳州市', value: '350600' },
  ]},
  { label: '江西', value: '360000', children: [
    { label: '南昌市', value: '360100' }, { label: '景德镇市', value: '360200' },
    { label: '萍乡市', value: '360300' }, { label: '九江市', value: '360400' },
  ]},
  { label: '山东', value: '370000', children: [
    { label: '济南市', value: '370100' }, { label: '青岛市', value: '370200' },
    { label: '淄博市', value: '370300' }, { label: '枣庄市', value: '370400' },
    { label: '东营市', value: '370500' }, { label: '烟台市', value: '370600' },
  ]},
  { label: '河南', value: '410000', children: [
    { label: '郑州市', value: '410100' }, { label: '开封市', value: '410200' },
    { label: '洛阳市', value: '410300' }, { label: '平顶山市', value: '410400' },
    { label: '安阳市', value: '410500' }, { label: '鹤壁市', value: '410600' },
    { label: '新乡市', value: '410700' }, { label: '焦作市', value: '410800' },
    { label: '濮阳市', value: '410900' }, { label: '许昌市', value: '411000' },
    { label: '漯河市', value: '411100' }, { label: '三门峡市', value: '411200' },
    { label: '南阳市', value: '411300' }, { label: '商丘市', value: '411400' },
    { label: '信阳市', value: '411500' }, { label: '周口市', value: '411600' },
    { label: '驻马店市', value: '411700' },
  ]},
  { label: '湖北', value: '420000', children: [
    { label: '武汉市', value: '420100' }, { label: '黄石市', value: '420200' },
    { label: '十堰市', value: '420300' }, { label: '宜昌市', value: '420500' },
  ]},
  { label: '湖南', value: '430000', children: [
    { label: '长沙市', value: '430100' }, { label: '株洲市', value: '430200' },
    { label: '湘潭市', value: '430300' }, { label: '衡阳市', value: '430400' },
  ]},
  { label: '广东', value: '440000', children: [
    { label: '广州市', value: '440100' }, { label: '韶关市', value: '440200' },
    { label: '深圳市', value: '440300' }, { label: '珠海市', value: '440400' },
    { label: '汕头市', value: '440500' }, { label: '佛山市', value: '440600' },
    { label: '江门市', value: '440700' }, { label: '湛江市', value: '440800' },
    { label: '茂名市', value: '440900' }, { label: '肇庆市', value: '441200' },
    { label: '惠州市', value: '441300' }, { label: '梅州市', value: '441400' },
    { label: '汕尾市', value: '441500' }, { label: '河源市', value: '441600' },
    { label: '阳江市', value: '441700' }, { label: '清远市', value: '441800' },
    { label: '东莞市', value: '441900' }, { label: '中山市', value: '442000' },
  ]},
  { label: '广西', value: '450000', children: [
    { label: '南宁市', value: '450100' }, { label: '柳州市', value: '450200' },
    { label: '桂林市', value: '450300' }, { label: '梧州市', value: '450400' },
  ]},
  { label: '海南', value: '460000', children: [
    { label: '海口市', value: '460100' }, { label: '三亚市', value: '460200' },
  ]},
  { label: '重庆', value: '500000', children: [{ label: '重庆市', value: '500100' }] },
  { label: '四川', value: '510000', children: [
    { label: '成都市', value: '510100' }, { label: '自贡市', value: '510300' },
    { label: '攀枝花市', value: '510400' }, { label: '泸州市', value: '510500' },
    { label: '德阳市', value: '510600' }, { label: '绵阳市', value: '510700' },
  ]},
  { label: '贵州', value: '520000', children: [
    { label: '贵阳市', value: '520100' }, { label: '六盘水市', value: '520200' },
    { label: '遵义市', value: '520300' }, { label: '安顺市', value: '520400' },
  ]},
  { label: '云南', value: '530000', children: [
    { label: '昆明市', value: '530100' }, { label: '曲靖市', value: '530300' },
    { label: '玉溪市', value: '530400' }, { label: '保山市', value: '530500' },
  ]},
  { label: '西藏', value: '540000', children: [
    { label: '拉萨市', value: '540100' }, { label: '日喀则市', value: '540200' },
  ]},
  { label: '陕西', value: '610000', children: [
    { label: '西安市', value: '610100' }, { label: '铜川市', value: '610200' },
    { label: '宝鸡市', value: '610300' }, { label: '咸阳市', value: '610400' },
  ]},
  { label: '甘肃', value: '620000', children: [
    { label: '兰州市', value: '620100' }, { label: '嘉峪关市', value: '620200' },
    { label: '金昌市', value: '620300' }, { label: '白银市', value: '620400' },
  ]},
  { label: '青海', value: '630000', children: [
    { label: '西宁市', value: '630100' }, { label: '海东市', value: '630200' },
  ]},
  { label: '宁夏', value: '640000', children: [
    { label: '银川市', value: '640100' }, { label: '石嘴山市', value: '640200' },
  ]},
  { label: '新疆', value: '650000', children: [
    { label: '乌鲁木齐市', value: '650100' }, { label: '克拉玛依市', value: '650200' },
  ]},
  { label: '台湾', value: '710000', children: [{ label: '台北市', value: '710100' }] },
  { label: '香港', value: '810000', children: [{ label: '香港特别行政区', value: '810100' }] },
  { label: '澳门', value: '820000', children: [{ label: '澳门特别行政区', value: '820100' }] },
];

interface CustomConditionModalProps {
  visible: boolean;
  onClose: () => void;
  onAdd: (condition: any) => void;
}

const CustomConditionModal: React.FC<CustomConditionModalProps> = ({
  visible,
  onClose,
  onAdd,
}) => {
  const [fields, setFields] = useState<FilterField[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedTag, setSelectedTag] = useState<FilterField | null>(null);
  const [conditionValue, setConditionValue] = useState<any>(null);

  // 地区选择器状态
  const [regionVisible, setRegionVisible] = useState(false);
  const [regionStep, setRegionStep] = useState<'province' | 'city'>('province');
  const [tempProvince, setTempProvince] = useState<any>(null);

  useEffect(() => {
    if (visible) {
      setLoading(true);
      getIndustryOptions()
        .then(res => setFields(res || []))
        .finally(() => setLoading(false));
    }
  }, [visible]);

  const handleTagSelect = (tag: FilterField) => {
    setSelectedTag(tag);
    setConditionValue(null);
  };

  const handleValueChange = (value: any) => {
    setConditionValue(value);
  };

  const handleSubmit = () => {
    if (!selectedTag || (conditionValue === null || conditionValue === undefined || conditionValue === '')) return;

    let displayValue = conditionValue;
    let operator = '=';

    if (selectedTag.type === 'select' && selectedTag.options) {
      const option = selectedTag.options.find((opt: any) => opt.value === conditionValue);
      displayValue = option ? option.label : conditionValue;
    } else if (selectedTag.type === 'number') {
      operator = '>=';
    } else if (selectedTag.type === 'friend_search') {
      operator = 'like';
      displayValue = `包含"${conditionValue}"`;
    }

    const condition = {
      type: "field",
      field: selectedTag.field,
      operator: operator,
      value: conditionValue,
      displayValue: displayValue,
      label: selectedTag.label,
      fieldType: selectedTag.type,
    };

    onAdd(condition);
    onClose();
    setSelectedTag(null);
    setConditionValue(null);
  };

  const renderRegionPicker = () => {
    return (
      <Popup
        visible={regionVisible}
        onMaskClick={() => setRegionVisible(false)}
        position="bottom"
        bodyStyle={{ height: '70vh', borderTopLeftRadius: '20px', borderTopRightRadius: '20px' }}
      >
        <div className={styles.regionDrillDown}>
          <div className={styles.regionDrillHeader}>
            {regionStep === 'city' ? (
              <Button
                fill="none"
                size="small"
                onClick={() => setRegionStep('province')}
                className={styles.backBtn}
              >
                ← 返回省份
              </Button>
            ) : (
              <span className={styles.regionDrillTitle}>选择地区</span>
            )}
            <Button fill="none" size="small" onClick={() => setRegionVisible(false)} className={styles.closeBtn}>取消</Button>
          </div>

          <div className={styles.regionDrillContent}>
            {regionStep === 'province' ? (
              <List className={styles.flatList}>
                {areaData.map(item => (
                  <List.Item
                    key={item.value}
                    onClick={() => {
                      const provinceName = item.label.replace(/省$/, '');
                      setTempProvince({ ...item, label: provinceName });
                      setRegionStep('city');
                    }}
                    arrow={true}
                  >
                    {item.label}
                  </List.Item>
                ))}
              </List>
            ) : (
              <List className={styles.flatList}>
                <List.Item
                  onClick={() => {
                    handleValueChange(tempProvince.label);
                    setRegionVisible(false);
                  }}
                  className={styles.allProvinceOption}
                  arrow={false}
                >
                  <span className={styles.primaryText}>选择全省：{tempProvince.label}</span>
                </List.Item>

                <div className={styles.listDivider}>选择城市</div>

                {tempProvince.children?.map((item: any) => (
                  <List.Item
                    key={item.value}
                    onClick={() => {
                      const cityName = item.label.replace(/市$/, '');
                      handleValueChange(`${tempProvince.label} ${cityName}`);
                      setRegionVisible(false);
                    }}
                    arrow={false}
                  >
                    {item.label}
                  </List.Item>
                ))}
              </List>
            )}
          </div>
        </div>
      </Popup>
    );
  };

  const renderValueInput = () => {
    if (!selectedTag) return null;

    switch (selectedTag.type) {
      case "friend_search":
        return (
          <div style={{ marginTop: '12px' }}>
            <div className={styles.inputWrapper}>
              <Input
                placeholder={selectedTag.placeholder || "输入昵称、微信号、手机号搜索"}
                value={conditionValue}
                onChange={handleValueChange}
                clearable
              />
            </div>
            <div className={styles.searchTip}>
              输入关键词后，将筛选出匹配的好友
            </div>
          </div>
        );

      case "province":
        return (
          <div style={{ marginTop: '12px' }}>
            <div
              className={styles.nativeTrigger}
              onClick={() => {
                setRegionVisible(true);
                setRegionStep('province');
              }}
            >
              <span className={styles.triggerLabel}>地区：</span>
              <span className={conditionValue ? styles.triggerValueActive : styles.triggerPlaceholder}>
                {conditionValue || '请选择'}
              </span>
              <span className={styles.triggerArrow}>›</span>
            </div>
            {renderRegionPicker()}
          </div>
        );

      case "select":
        return (
          <Selector
            columns={2}
            options={selectedTag.options || []}
            value={[conditionValue]}
            onChange={v => handleValueChange(v[0])}
            style={{
              '--border-radius': '12px',
              '--padding': '12px 16px',
            }}
          />
        );

      case "number":
        return (
          <div className={styles.inputWrapper}>
            <Input
              placeholder={`请输入${selectedTag.label}数值`}
              type="number"
              value={conditionValue}
              onChange={handleValueChange}
            />
          </div>
        );

      case "input":
      default:
        return (
          <div className={styles.inputWrapper}>
            <Input
              placeholder={`请输入${selectedTag.label}`}
              value={conditionValue}
              onChange={handleValueChange}
            />
          </div>
        );
    }
  };

  return (
    <Popup
      visible={visible}
      onMaskClick={onClose}
      position="bottom"
      bodyStyle={{ height: "80vh", borderTopLeftRadius: '24px', borderTopRightRadius: '24px' }}
    >
      <div className={styles.container}>
        <div className={styles.header}>
          <div className={styles.title}>添加筛选条件</div>
          <Button size="small" fill="none" onClick={onClose} style={{ color: '#666' }}>
            取消
          </Button>
        </div>

        <div className={styles.content}>
          <div className={styles.section}>
            <div className={styles.sectionTitle}>选择维度</div>
            <div className={styles.tagList}>
              {loading ? (
                <div style={{ textAlign: "center", padding: "40px", color: "#9ca3af" }}>
                  加载中...
                </div>
              ) : (
                fields.map(field => (
                  <div
                    key={field.field}
                    className={`${styles.tagItem} ${
                      selectedTag?.field === field.field ? styles.selected : ""
                    }`}
                    onClick={() => handleTagSelect(field)}
                  >
                    {field.label}
                  </div>
                ))
              )}
            </div>
          </div>

          {selectedTag && (
            <div className={styles.section}>
              <div className={styles.sectionTitle}>设定条件</div>
              {renderValueInput()}
            </div>
          )}
        </div>

        <div className={styles.footer}>
          <Button
            color="primary"
            block
            disabled={!selectedTag || (conditionValue === null || conditionValue === undefined || conditionValue === '')}
            onClick={handleSubmit}
            className={styles.submitBtn}
          >
            确认添加
          </Button>
        </div>
      </div>
    </Popup>
  );
};

export default CustomConditionModal;
