import React, { useState, useEffect, useRef } from "react";
import { Input, Button, Tag, Switch, Spin, message, Modal } from "antd";
import {
  PlusOutlined,
  EyeOutlined,
  CloseOutlined,
  DownloadOutlined,
  SearchOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { uploadFile } from "@/api/common";
import styles from "./base.module.scss";
import { posterTemplates } from "./base.data";
import GroupSelection from "@/components/GroupSelection";
import FileUpload from "@/components/Upload/FileUpload";
import { GroupSelectionItem } from "@/components/GroupSelection/data";

interface BasicSettingsProps {
  isEdit: boolean;
  formData: any;
  onChange: (data: any) => void;
  sceneList: any[];
  sceneLoading: boolean;
}

interface Material {
  id: string;
  name: string;
  type: string;
  url: string;
}

const generatePosterMaterials = (): Material[] => {
  return posterTemplates.map(template => ({
    id: template.id,
    name: template.name,
    type: "poster",
    url: template.url,
  }));
};

const BasicSettings: React.FC<BasicSettingsProps> = ({
  isEdit,
  formData,
  onChange,
  sceneList,
  sceneLoading,
}) => {
  const [isPreviewOpen, setIsPreviewOpen] = useState(false);
  const [materials] = useState<Material[]>(generatePosterMaterials());
  const [selectedMaterials, setSelectedMaterials] = useState<Material[]>(
    formData.posters?.length > 0 ? formData.posters : [],
  );

  // 自定义标签相关状态
  const [customTagInput, setCustomTagInput] = useState("");
  const [customTagsOptions, setCustomTagsOptions] = useState<string[]>(
    formData.customTagsOptions || [],
  );
  const [tips, setTips] = useState(formData.tips || "");
  const [selectedScenarioTags, setSelectedScenarioTags] = useState(
    formData.scenarioTags || [],
  );
  const [selectedCustomTags, setSelectedCustomTags] = useState(
    formData.customTags || [],
  );
  // 电话获客相关状态
  const [phoneSettings, setPhoneSettings] = useState({
    autoAdd: formData.phoneSettings?.autoAdd ?? true,
    speechToText: formData.phoneSettings?.speechToText ?? true,
    questionExtraction: formData.phoneSettings?.questionExtraction ?? true,
  });


  // 新增：自定义海报相关状态
  const [customPosters, setCustomPosters] = useState<Material[]>([]);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);

  // 新增：用于文件选择的ref
  const uploadInputRef = useRef<HTMLInputElement>(null);

  // 初始化时，如果没有选择场景，默认选择海报获客
  useEffect(() => {
    if (!formData.scenario) {
      onChange({ ...formData, scenario: "haibao" });
    }
  }, [formData, onChange]);

  // 监听 formData 变化，同步自定义标签和获客标签状态
  useEffect(() => {
    setCustomTagsOptions(formData.customTagsOptions || []);
    setSelectedCustomTags(formData.customTags || []);
  }, [formData.customTagsOptions, formData.customTags]);

  // 监听获客标签变化
  useEffect(() => {
    setSelectedScenarioTags(formData.scenarioTags || []);
  }, [formData.scenarioTags]);

  useEffect(() => {
    setTips(formData.tips || "");
  }, [formData.tips]);

  // 当切换到海报场景且 tips 为空时，设置默认值
  useEffect(() => {
    if (formData.scenario === 1 && !formData.tips) {
      const defaultTips = "请注意消息，稍后加你微信";
      onChange({ ...formData, tips: defaultTips });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formData.scenario]);


  // 选中场景
  const handleScenarioSelect = (sceneId: number) => {
    onChange({ ...formData, scenario: sceneId });
  };

  // 选中/取消标签
  const handleScenarioTagToggle = (tag: string) => {
    const newTags = selectedScenarioTags.includes(tag)
      ? selectedScenarioTags.filter((t: string) => t !== tag)
      : [...selectedScenarioTags, tag];
    setSelectedScenarioTags(newTags);
    onChange({ ...formData, scenarioTags: newTags });
  };

  const handleCustomTagToggle = (tag: string) => {
    const newTags = selectedCustomTags.includes(tag)
      ? selectedCustomTags.filter((t: string) => t !== tag)
      : [...selectedCustomTags, tag];
    setSelectedCustomTags(newTags);
    onChange({ ...formData, customTags: newTags });
  };
  // 添加自定义标签
  const handleAddCustomTag = () => {
    if (!customTagInput.trim()) return;
    const newTag = customTagInput.trim();
    // 已存在则忽略
    if (customTagsOptions.includes(newTag)) {
      // 若未选中则顺便选中
      const maybeSelected = selectedCustomTags.includes(newTag)
        ? selectedCustomTags
        : [...selectedCustomTags, newTag];
      setSelectedCustomTags(maybeSelected);
      onChange({ ...formData, customTags: maybeSelected });
      setCustomTagInput("");
      return;
    }

    const updatedOptions = [...customTagsOptions, newTag];
    const updatedSelected = [...selectedCustomTags, newTag];
    setCustomTagsOptions(updatedOptions);
    setSelectedCustomTags(updatedSelected);
    setCustomTagInput("");
    onChange({
      ...formData,
      customTagsOptions: updatedOptions,
      customTags: updatedSelected,
    });
  };

  // 删除自定义标签
  const handleRemoveCustomTag = (tagName: string) => {
    const updatedOptions = customTagsOptions.filter(
      (tag: string) => tag !== tagName,
    );
    setCustomTagsOptions(updatedOptions);

    // 同时从选中的自定义标签中移除
    const updatedSelectedCustom = selectedCustomTags.filter(
      (t: string) => t !== tagName,
    );
    setSelectedCustomTags(updatedSelectedCustom);

    onChange({
      ...formData,
      customTagsOptions: updatedOptions,
      customTags: updatedSelectedCustom,
    });
  };

  // 新增：删除自定义海报
  const handleRemoveCustomPoster = (id: string) => {
    setCustomPosters(prev => prev.filter(p => p.id !== id));
    // 如果选中则取消选中
    if (selectedMaterials.some(m => m.id === id)) {
      setSelectedMaterials([]);
      onChange({ ...formData, posters: [] });
    }
  };

  // 修改：选中/取消选中海报
  const handleMaterialSelect = (material: Material) => {
    const isSelected = selectedMaterials.some(m => m.id === material.id);
    if (isSelected) {
      setSelectedMaterials([]);
      onChange({ ...formData, posters: [] });
    } else {
      setSelectedMaterials([material]);
      onChange({ ...formData, posters: [material] });
    }
  };

  // 新增：全屏预览
  const handlePreviewImage = (url: string) => {
    setPreviewUrl(url);
    setIsPreviewOpen(true);
  };

  // 下载模板
  const handleDownloadTemplate = () => {
    const template =
      "姓名/备注,电话号码,微信号,来源,订单金额,下单日期\n张三,13800138000,wxid_123,抖音,99.00,2024-03-03";
    const blob = new Blob([template], { type: "text/csv" });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "订单导入模板.csv";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  };

  // 当前选中的场景对象
  const currentScene = sceneList.find(s => s.id === formData.scenario);
  //打开订单
  const openOrder =
    formData.scenario !== 2 ? { display: "none" } : { display: "block" };

  const openPoster =
    formData.scenario !== 1 ? { display: "none" } : { display: "block" };

  const handleWechatGroupSelect = (groups: GroupSelectionItem[]) => {
    onChange({
      ...formData,
      wechatGroups: groups.map(v => v.id),
      wechatGroupsOptions: groups,
    });
  };


  return (
    <div className={styles["basic-container"]}>
      {/* 场景选择区块 */}
      <div className={styles["basic-scene-select"]}>
        {sceneLoading ? (
          <div
            style={{
              display: "flex",
              justifyContent: "center",
              alignItems: "center",
              minHeight: 80,
            }}
          >
            <Spin size="large"></Spin>
          </div>
        ) : (
          <div className={styles["basic-scene-grid"]}>
            {sceneList
             .filter(scene => {
               // 编辑模式下，如果当前选中的场景 id 是 10，则显示它
               if (isEdit && formData.scenario === 10 && scene.id === 10) {
                 return true;
               }
               // 其他情况过滤掉 id 为 10 的场景
               return scene.id !== 10;
             })
             .map(scene => {
              const selected = formData.scenario === scene.id;
              // 编辑模式下，如果当前场景 id 是 10，则禁用所有场景选择
              const isDisabled = isEdit && formData.scenario === 10;
              return (
                <button
                  key={scene.id}
                  onClick={() => !isDisabled && handleScenarioSelect(scene.id)}
                  disabled={isDisabled}
                  className={
                    styles["basic-scene-btn"] +
                    (selected ? " " + styles.selected : "") +
                    (isDisabled ? " " + styles.disabled : "")
                  }
                >
                  {scene.name.replace("获客", "")}
                </button>
              );
            })}
          </div>
        )}
      </div>
      {/* 计划名称输入区 */}
      <div className={styles["basic-label"]}>计划名称</div>
      <div className={styles["basic-input-block"]}>
        <Input
          value={formData.name}
          onChange={e =>
            onChange({ ...formData, name: String(e.target.value) })
          }
          placeholder="请输入计划名称"
        />
      </div>
      <div className={styles["basic-label"]}>获客标签（可多选）</div>
      {/* 标签选择区块 */}
      {formData.scenario && (
        <div className={styles["basic-tag-list"]}>
          {(currentScene?.scenarioTags || []).map((tag: string) => (
            <Tag
              key={tag}
              color={selectedScenarioTags.includes(tag) ? "blue" : "default"}
              onClick={() => handleScenarioTagToggle(tag)}
              className={styles["basic-tag-item"]}
            >
              {tag}
            </Tag>
          ))}
          {/* 自定义标签 */}
          {customTagsOptions.map((tag: string) => (
            <Tag
              key={tag}
              color={selectedCustomTags.includes(tag) ? "blue" : "default"}
              onClick={() => handleCustomTagToggle(tag)}
              closable
              onClose={() => handleRemoveCustomTag(tag)}
              className={styles["basic-tag-item"]}
            >
              {tag}
            </Tag>
          ))}
        </div>
      )}
      {/* 自定义标签输入区 */}
      <div className={styles["basic-custom-tag-input"]}>
        <Input
          type="text"
          value={customTagInput}
          onChange={e => setCustomTagInput(e.target.value)}
          onPressEnter={handleAddCustomTag}
          placeholder="添加自定义标签"
        />
        <Button
          type="primary"
          onClick={handleAddCustomTag}
          disabled={!customTagInput.trim()}
        >
          添加
        </Button>
      </div>
      {/* 输入获客成功提示 - 只有海报场景才显示 */}
      {formData.scenario === 1 && (
        <>
          <div className={styles["basic-label"]}>请输入获客成功提示</div>
          <div className={styles["basic-success-tip"]}>
            <Input
              type="text"
              value={tips}
              onChange={e => {
                setTips(e.target.value);
                onChange({ ...formData, tips: e.target.value });
              }}
              placeholder="请输入获客成功提示"
            />
          </div>
        </>
      )}
      {/* 选素材 */}
      <div className={styles["basic-materials"]} style={openPoster}>
        <div className={styles["basic-label"]}>选择海报</div>
        <div className={styles["basic-materials-grid"]}>
          {[...materials, ...customPosters].map(material => {
            const isSelected = selectedMaterials.some(
              m => m.id === material.id,
            );
            const isCustom = material.id.startsWith("custom-");
            return (
              <div
                key={material.id}
                className={
                  styles["basic-material-card"] +
                  (isSelected ? " " + styles.selected : "")
                }
                onClick={() => handleMaterialSelect(material)}
              >
                {/* 预览按钮：自定义海报在左上，内置海报在右上 */}
                <span
                  className={styles["basic-material-preview"]}
                  onClick={e => {
                    e.stopPropagation();
                    handlePreviewImage(material.url);
                  }}
                >
                  <EyeOutlined
                    style={{ color: "#fff", width: 18, height: 18 }}
                  />
                </span>
                {/* 删除自定义海报按钮 */}
                {isCustom && (
                  <Button
                    style={{
                      position: "absolute",
                      top: 8,
                      right: 8,
                      width: 28,
                      height: 28,
                      background: "rgba(0,0,0,0.5)",
                      border: "none",
                      borderRadius: "50%",
                      zIndex: 2,
                      cursor: "pointer",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      lineHeight: 20,
                      color: "#ffffff",
                    }}
                    onClick={e => {
                      e.stopPropagation();
                      handleRemoveCustomPoster(material.id);
                    }}
                  >
                    <CloseOutlined />
                  </Button>
                )}
                <img
                  src={material.url}
                  alt={material.name}
                  className={styles["basic-material-img"]}
                />
                <div className={styles["basic-material-name"]}>
                  {material.name}
                </div>
              </div>
            );
          })}
          {/* 添加海报卡片 */}
          <div
            className={styles["basic-add-material"]}
            onClick={() => uploadInputRef.current?.click()}
          >
            <span style={{ fontSize: 36, color: "#bbb", marginBottom: 8 }}>
              <PlusOutlined />
            </span>
            <span style={{ color: "#888" }}>添加海报</span>
            <input
              ref={uploadInputRef}
              type="file"
              accept="image/*"
              style={{ display: "none" }}
              onChange={async e => {
                const file = e.target.files?.[0];
                if (file) {
                  // 直接上传
                  try {
                    const url = await uploadFile(file);
                    const newPoster = {
                      id: `custom-${Date.now()}`,
                      name: "自定义海报",
                      type: "poster",
                      url: url,
                    };
                    setCustomPosters(prev => [...prev, newPoster]);
                  } catch (err) {
                    // 可加toast提示
                  }
                  e.target.value = "";
                }
              }}
            />
          </div>
        </div>
        {/* 全屏图片预览 */}
        <Modal
          open={isPreviewOpen}
          onCancel={() => {
            setIsPreviewOpen(false);
            setPreviewUrl(null);
          }}
          footer={null}
          width={800}
        >
          {previewUrl && (
            <img
              src={previewUrl}
              alt="Preview"
              style={{ width: "100%", height: "100%" }}
            />
          )}
        </Modal>
      </div>
      {/* 群选择 - 只有微信群场景才显示 */}
      {formData.scenario === 7 && (
        <div className={styles["basic-group-selection"]}>
          <div className={styles["basic-label"]}>选择群聊</div>
          <GroupSelection
            selectedOptions={formData.wechatGroupsOptions || []}
            onSelect={handleWechatGroupSelect}
            placeholder="请选择微信群"
            className={styles["basic-group-selector"]}
          />
        </div>
      )}

      {/* 订单导入区块 - 使用FileUpload组件 */}
      <div className={styles["basic-order-upload"]} style={openOrder}>
        <div className={styles["basic-order-upload-label"]}>订单表格上传</div>
        <div className={styles["basic-order-upload-actions"]}>
          <Button
            style={{ display: "flex", alignItems: "center", gap: 4 }}
            onClick={handleDownloadTemplate}
          >
            <DownloadOutlined style={{ fontSize: 18 }} /> 下载模板
          </Button>
        </div>
        <div className={styles["basic-order-upload-file"]}>
          <FileUpload
            value={formData.orderFileUrl || ""}
            onChange={url => onChange({ ...formData, orderFileUrl: url })}
            acceptTypes={["excel"]}
            maxCount={1}
            maxSize={10}
            showPreview={false}
          />
        </div>
        <div className={styles["basic-order-upload-tip"]}>
          支持 Excel 格式，上传后将文件保存到服务器
        </div>
      </div>
      {/* 电话获客设置区块，仅在选择电话获客场景时显示 */}
      {formData.scenario === 5 && (
        <div className={styles["basic-phone-settings"]}>
          <div style={{ fontWeight: 600, fontSize: 16, marginBottom: 16 }}>
            电话获客设置
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
              }}
            >
              <span>自动加好友</span>
              <Switch
                checked={phoneSettings.autoAdd}
                onChange={v => setPhoneSettings(s => ({ ...s, autoAdd: v }))}
              />
            </div>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
              }}
            >
              <span>语音转文字</span>
              <Switch
                checked={phoneSettings.speechToText}
                onChange={v =>
                  setPhoneSettings(s => ({ ...s, speechToText: v }))
                }
              />
            </div>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
              }}
            >
              <span>问题提取</span>
              <Switch
                checked={phoneSettings.questionExtraction}
                onChange={v =>
                  setPhoneSettings(s => ({ ...s, questionExtraction: v }))
                }
              />
            </div>
          </div>
        </div>
      )}

      <div className={styles["basic-footer-switch"]}>
        <span>是否启用</span>
        <Switch
          checked={formData.status === 1}
          onChange={value => onChange({ ...formData, status: value ? 1 : 0 })}
        />
      </div>

    </div>
  );
};

export default BasicSettings;
