import { useMemo } from "react";
import styles from "./GradientEditor.module.css";

interface ColorStop {
  color: string;
  position: string;
}

interface Props {
  value: string;
  onChange: (value: string) => void;
}

/**
 * 解析 CSS linear-gradient 字符串，提取方向和色标。
 * 例如: "linear-gradient(160deg, #fff9f2 0%, #ffeedd 100%)"
 */
function parseGradient(gradient: string): { direction: string; stops: ColorStop[] } | null {
  const match = gradient.match(/linear-gradient\(([^,]+),\s*(.+)\)/);
  if (!match) return null;

  const direction = match[1].trim();
  const stopsStr = match[2];

  // 分割色标: "#fff9f2 0%, #ffeedd 100%"
  const stops: ColorStop[] = [];
  const parts = stopsStr.split(/,(?![^(]*\))/); // split on commas not inside parens
  for (const part of parts) {
    const trimmed = part.trim();
    // 匹配: <color> <position>
    const m = trimmed.match(/^(.+?)\s+(\d+%)$/);
    if (m) {
      stops.push({ color: m[1].trim(), position: m[2] });
    } else {
      // 可能只有颜色, 没有位置
      stops.push({ color: trimmed, position: "" });
    }
  }

  return { direction, stops };
}

function buildGradient(direction: string, stops: ColorStop[]): string {
  const stopsStr = stops
    .map((s) => (s.position ? `${s.color} ${s.position}` : s.color))
    .join(", ");
  return `linear-gradient(${direction}, ${stopsStr})`;
}

export default function GradientEditor({ value, onChange }: Props) {
  const parsed = useMemo(() => parseGradient(value), [value]);

  if (!parsed) {
    // 无法解析时退化为纯文本输入
    return (
      <input
        type="text"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className={styles.fallback}
      />
    );
  }

  function updateStopColor(index: number, color: string) {
    const newStops = parsed!.stops.map((s, i) =>
      i === index ? { ...s, color } : s
    );
    onChange(buildGradient(parsed!.direction, newStops));
  }

  return (
    <div className={styles.wrapper}>
      {/* 渐变色预览条 */}
      <div
        className={styles.preview}
        style={{ background: value }}
        title={value}
      />

      {/* 各色标取色器 */}
      <div className={styles.stops}>
        {parsed.stops.map((stop, i) => (
          <div key={i} className={styles.stopItem}>
            <input
              type="color"
              value={stop.color}
              onChange={(e) => updateStopColor(i, e.target.value)}
              className={styles.colorPicker}
            />
            <span className={styles.stopLabel}>
              {stop.color}
              {stop.position && ` ${stop.position}`}
            </span>
          </div>
        ))}
      </div>

      {/* 原始值（可手动编辑） */}
      <input
        type="text"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className={styles.rawInput}
      />
    </div>
  );
}
