import React, { useState, useEffect } from "react";
import axios from "axios";
import { ResponsiveBoxPlot } from "@nivo/boxplot";
import PointCloud from "../components/PointCloud";
import "../style.css";

const GeneView: React.FC = () => {
  const [gene, setGene] = useState("");
  const [data, setData] = useState<any[]>([]);
  const [cellData, setCellData] = useState<any[]>([]);
  const [distributionData, setDistributionData] = useState<any>({ data: [], colorObj: {}, cellTypes: [] });
  const [loading, setLoading] = useState(false);
  const [cellLoading, setCellLoading] = useState(false);
  const [error, setError] = useState("");
  const [cellError, setCellError] = useState("");
  const [availableGenes, setAvailableGenes] = useState<string[]>([]);
  const [selectedStage, setSelectedStage] = useState("CS7");

  // 为细胞类型生成颜色映射（与 PointCloud 组件保持一致）
  const generateCellTypeColors = (cellTypes: string[]) => {
    const colorMap = new Map<string, string>();
    const colors = [
      '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
      '#DDA0DD', '#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9',
      '#F8C471', '#82E0AA', '#F1948A', '#85CDCE', '#D7BDE2',
      '#A9DFBF', '#F9E79F', '#D5A6BD', '#AED6F1', '#E8DAEF'
    ];

    cellTypes.forEach((type, index) => {
      colorMap.set(type, colors[index % colors.length]);
    });

    return colorMap;
  };

  // 动态获取某个阶段的基因列表
  useEffect(() => {
    if (!selectedStage) return;
    axios
      .get("http://localhost:5000/api/genes", {
        params: { stage: selectedStage },
      })
      .then((res) => setAvailableGenes(res.data))
      .catch(() => setAvailableGenes([]));
  }, [selectedStage]);

  // 获取细胞类型数据
  useEffect(() => {
    if (!selectedStage) return;

    setCellLoading(true);
    setCellError("");
    setCellData([]);

    axios
      .get("http://localhost:5000/api/cell", {
        params: { stage: selectedStage },
      })
      .then((res) => {
        setCellData(res.data.cells);
      })
      .catch((err) => {
        if (err.response && err.response.data?.error) {
          setCellError(err.response.data.error);
        } else {
          setCellError("Failed to fetch cell type data.");
        }
      })
      .finally(() => {
        setCellLoading(false);
      });
  }, [selectedStage]);

  const handleSearch = async () => {
    if (!gene) return;

    setLoading(true);
    setError("");
    setData([]);
    setDistributionData({ data: [], colorObj: {}, cellTypes: [] });

    try {
      // 同时请求基因表达和分布数据
      const [expressionRes, distributionRes] = await Promise.all([
        axios.get("http://localhost:5000/api/gene_expression", {
          params: {
            gene: gene.trim(),
            stage: selectedStage,
          },
        }),
        axios.get("http://localhost:5000/api/gene_dist", {
          params: {
            gene: gene.trim(),
            stage: selectedStage,
          },
        }),
      ]);

      if (expressionRes.data.expression.length === 0) {
        setError("No expression data found.");
      } else {
        setData(expressionRes.data.expression);

        // 转换分布数据为 nivo boxplot 格式 - 需要扁平化为原始数据点
        const boxplotData: any[] = [];
        const cellTypes = Object.keys(distributionRes.data.distribution).sort();
        const colorMap = generateCellTypeColors(cellTypes);

        Object.entries(distributionRes.data.distribution).forEach(
          ([cellType, values]: [string, any]) => {
            values.forEach((value: number) => {
              boxplotData.push({
                group: cellType,
                value: value,
              });
            });
          }
        );

        // 创建颜色对象映射
        const colorObj: { [key: string]: string } = {};
        cellTypes.forEach(cellType => {
          colorObj[cellType] = colorMap.get(cellType) || '#CCCCCC';
        });

        setDistributionData({ data: boxplotData, colorObj, cellTypes });
      }
    } catch (err: any) {
      if (err.response && err.response.data?.error) {
        setError(err.response.data.error);
      } else {
        setError("Failed to fetch data.");
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="page-container">
      <div className="page-header">
        <h1>Gene Expression</h1>
        <p className="page-description">
          查看和分析不同发育阶段的基因表达模式和空间分布。通过3D可视化探索基因在胚胎发育过程中的表达变化。
        </p>
      </div>

      <div className="page-content">
        {/* 基因表达查询控制器 */}
        <div className="query-controls" style={{
          display: "flex",
          alignItems: "center",
          gap: "2rem",
          flexWrap: "wrap",
          marginBottom: "2rem"
        }}>
          <label>
            发育阶段:&nbsp;
            <select
              value={selectedStage}
              onChange={(e) => {
                setSelectedStage(e.target.value);
                setGene("");
                setData([]);
                setDistributionData([]);
                setError("");
              }}
            >
              <option value="CS7">CS7 - 早期发育阶段</option>
              <option value="CS8">CS8 - 中期发育阶段</option>
              <option value="CS9">CS9 - 后期发育阶段</option>
              <option value="CS11">CS11 - 后期发育阶段</option>
            </select>
          </label>

          <label htmlFor="gene-select">目标基因:</label>
          <select
            id="gene-select"
            aria-label="选择基因"
            value={gene}
            onChange={(e) => setGene(e.target.value)}
          >
            <option value="">-- 请选择基因 --</option>
            {availableGenes.map((g) => (
              <option key={g} value={g}>
                {g}
              </option>
            ))}
          </select>

          <button onClick={handleSearch} disabled={!gene || loading}>
            {loading ? "加载中..." : "查询表达"}
          </button>
        </div>

        {/* 错误提示 */}
        {error && <div className="error-message" style={{ marginBottom: "2rem" }}>{error}</div>}

        {/* 3D 可视化说明 */}
        <p className="flat-section-description">
          下方展示了{selectedStage}发育阶段的细胞类型分布（左）、所选基因的表达模式（中）和基因在各细胞类型中的表达分布（右）。
          点击任意数据点可查看详细信息。
        </p>

        {/* 三可视化区域 */}
        <div
          className="three-column-grid visualization-grid"
          style={{
            display: "grid",
            gridTemplateColumns: "700px 500px minmax(350px, 0.8fr)",
            gap: "2rem",
            minHeight: "600px",
            width: "100%",
            "--visualization-width": "500px"
          } as React.CSSProperties}
        >
            {/* 细胞类型可视化 */}
            <div className="visualization-container" style={{ width: "700px", minWidth: "700px", maxWidth: "700px" }}>
              <h3 style={{ textAlign: "center" }}>细胞类型分布</h3>
              {cellError && <div className="error-message">{cellError}</div>}
              {cellData.length > 0 ? (
                <div style={{ width: "700px", height: "100%" }}>
                  <PointCloud data={cellData} isCategorical={true} />
                </div>
              ) : (
                <div className="no-data-message">
                  {cellLoading ? (
                    <div>
                      <div style={{ fontSize: "2rem", marginBottom: "1rem" }}>🔄</div>
                      <p>正在加载细胞类型数据...</p>
                    </div>
                  ) : (
                    <div>
                      <div style={{ fontSize: "2rem", marginBottom: "1rem" }}>🧬</div>
                      <p>细胞类型分布</p>
                      <p style={{ fontSize: "0.9rem", color: "var(--text-secondary)" }}>
                        {selectedStage} 阶段
                      </p>
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* 基因表达可视化 */}
            <div className="visualization-container" style={{ width: "500px", minWidth: "500px", maxWidth: "500px" }}>
              <h3 style={{ textAlign: "center" }}>基因表达模式</h3>
              {data.length > 0 ? (
                <div style={{ width: "500px", height: "100%" }}>
                  <PointCloud data={data} autoRotate={true} />
                </div>
              ) : (
                <div className="no-data-message">
                  {loading ? (
                    <div>
                      <div style={{ fontSize: "2rem", marginBottom: "1rem" }}>🔄</div>
                      <p>正在加载基因表达数据...</p>
                    </div>
                  ) : (
                    <div>
                      <div style={{ fontSize: "2rem", marginBottom: "1rem" }}>📊</div>
                      <p>请选择目标基因以查看表达数据</p>
                      <p style={{ fontSize: "0.9rem", color: "var(--text-secondary)" }}>
                        当前阶段：{selectedStage}
                      </p>
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* 基因分布箱线图 */}
            <div className="visualization-container">
              <h3 style={{textAlign: "center" }}>基因表达分布</h3>
              {distributionData.data && distributionData.data.length > 0 ? (
                <div style={{ height: "480px" }}>
                  <ResponsiveBoxPlot
                    data={distributionData.data}
                    margin={{ top: 40, right: 100, bottom: 80, left: 140 }}
                    minValue="auto"
                    maxValue="auto"
                    padding={0.2}
                    enableGridX={true}
                    enableGridY={false}
                    gridXValues={3}
                    layout="horizontal"
                    axisTop={null}
                    axisRight={null}
                    axisBottom={{
                      tickSize: 5,
                      tickPadding: 12,
                      tickRotation: 0,
                      legend: "表达值",
                      legendPosition: "middle",
                      legendOffset: 60,
                      format: (value: number) => value.toFixed(2),
                      tickValues: 3,
                    }}
                    axisLeft={{
                      tickSize: 5,
                      tickPadding: 10,
                      tickRotation: 0,
                      legend: "细胞类型",
                      legendPosition: "middle",
                      legendOffset: -120,
                      format: (value: string) => value.length > 12 ? `${value.substring(0, 12)}...` : value,
                    }}
                    colors={(boxData: any) => {
                      // 根据 group 获取颜色
                      return distributionData.colorObj[boxData.group] || '#CCCCCC';
                    }}
                    borderRadius={2}
                    borderWidth={2}
                    borderColor={{
                      from: "color",
                      modifiers: [["darker", 0.3]],
                    }}
                    medianWidth={2}
                    medianColor={{
                      from: "color",
                      modifiers: [["darker", 0.3]],
                    }}
                    whiskerEndSize={0.6}
                    whiskerColor={{
                      from: "color",
                      modifiers: [["darker", 0.3]],
                    }}
                    motionConfig="gentle"
                    legends={[]}
                  />
                </div>
              ) : (
                <div className="no-data-message">
                  {loading ? (
                    <div>
                      <div style={{ fontSize: "2rem", marginBottom: "1rem" }}>🔄</div>
                      <p>正在加载分布数据...</p>
                    </div>
                  ) : (
                    <div>
                      <div style={{ fontSize: "2rem", marginBottom: "1rem" }}>📈</div>
                      <p>请选择目标基因以查看表达分布</p>
                      <p style={{ fontSize: "0.9rem", color: "var(--text-secondary)" }}>
                        箱线图显示各细胞类型中的表达分布
                      </p>
                    </div>
                  )}
                </div>
              )}
            </div>
          </div>

        <div className="section">
          <h2>使用说明</h2>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: "2rem", marginTop: "1.5rem" }}>
            <div>
              <h3>🎯 选择目标</h3>
              <p>首先选择感兴趣的发育阶段，系统将自动显示该阶段的细胞类型分布，然后选择基因查看表达模式。</p>
            </div>
            <div>
              <h3>🖱️ 交互操作</h3>
              <p>在3D视图中使用鼠标拖拽旋转视角，滚轮缩放，点击数据点查看详细信息。</p>
            </div>
            <div>
              <h3>🎨 颜色编码</h3>
              <p>左侧和右侧：相同颜色代表相同细胞类型，保持一致性便于对比。中间：颜色代表基因表达强度，红色表示高表达，蓝色表示低表达。</p>
            </div>
            <div>
              <h3>📈 箱线图解读</h3>
              <p>箱线图显示四分位数分布：箱体表示25%-75%范围，中线为中位数，胡须显示数据范围，点表示异常值。</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default GeneView;
