import { useState, useEffect, useRef } from "react";
import { CleanConfig } from "../types";
import layout from "./SettingsLayout.module.css";
import styles from "./RulesTab.module.css";
import { ToggleSwitch } from "./ToggleSwitch";

type SaveStatus = "idle" | "debouncing" | "saved";

type RulesTabProps = {
  config: CleanConfig;
  onUpdateConfig: (newConfig: Partial<CleanConfig>) => void;
};

export function RulesTab({ config, onUpdateConfig }: RulesTabProps) {
  const [customParamsInput, setCustomParamsInput] = useState(
    config.custom_params.join(", "),
  );
  const [saveStatus, setSaveStatus] = useState<SaveStatus>("idle");
  const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const savedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    return () => {
      if (debounceTimerRef.current) {
        clearTimeout(debounceTimerRef.current);
      }

      if (savedTimerRef.current) {
        clearTimeout(savedTimerRef.current);
      }
    };
  }, []);

  const handleCustomParamsChange = (value: string) => {
    setCustomParamsInput(value);
    setSaveStatus("debouncing");

    if (debounceTimerRef.current) {
      clearTimeout(debounceTimerRef.current);
    }

    if (savedTimerRef.current) {
      clearTimeout(savedTimerRef.current);
      savedTimerRef.current = null;
    }

    debounceTimerRef.current = setTimeout(() => {
      const params = value
        .split(",")
        .map((p) => p.trim())
        .filter((p) => p.length > 0);

      onUpdateConfig({ custom_params: params });
      setSaveStatus("saved");

      savedTimerRef.current = setTimeout(() => {
        setSaveStatus("idle");
      }, 1500);
    }, 500);
  };

  const renderSaveIndicator = () => {
    if (saveStatus === "idle") return null;

    return (
      <span
        className={`${styles["save-indicator"]} ${
          styles[`save-indicator--${saveStatus}`]
        }`}
      >
        {saveStatus === "debouncing" ? "..." : "\u2713"}
      </span>
    );
  };

  return (
    <div className="tab-content">
      <div className={layout["section"]}>
        <div className={layout["section-title"]}>Cleaning rules</div>
        <div className={layout["settings-list"]}>
          <div className={layout["settings-row"]}>
            <div className={layout["settings-info"]}>
              <div className={layout["settings-name"]}>
                Strip tracking parameters
              </div>
              <div className={layout["settings-desc"]}>
                Removes analytics tokens like utm_source, ref, fbclid, etc.
              </div>
            </div>
            <ToggleSwitch
              checked={config.strip_utms}
              onChange={(checked) => onUpdateConfig({ strip_utms: checked })}
            />
          </div>

          {config.strip_utms && (
            <div className={layout["settings-row"]}>
              <div className={layout["settings-info"]}>
                <div className={layout["settings-name"]}>
                  Additional parameters to strip
                </div>
                <div className={layout["settings-desc"]}>
                  Comma-separated list of custom parameter names.
                </div>
                <div className={styles["input-row"]}>
                  <input
                    type="text"
                    className={styles["custom-params-input"]}
                    placeholder="ref, tracking_id, campaign"
                    value={customParamsInput}
                    onChange={(e) => handleCustomParamsChange(e.target.value)}
                  />
                  {renderSaveIndicator()}
                </div>
              </div>
            </div>
          )}

          <div className={layout["settings-row"]}>
            <div className={layout["settings-info"]}>
              <div className={layout["settings-name"]}>
                Normalize typography
              </div>
              <div className={layout["settings-desc"]}>
                Replaces curly quotes, em dashes, and en dashes with plain ASCII
                equivalents.
              </div>
            </div>
            <ToggleSwitch
              checked={config.fix_quotes}
              onChange={(checked) => onUpdateConfig({ fix_quotes: checked })}
            />
          </div>

          <div className={layout["settings-row"]}>
            <div className={layout["settings-info"]}>
              <div className={layout["settings-name"]}>
                Clean trailing newlines
              </div>
              <div className={layout["settings-desc"]}>
                Trims duplicate carriage returns and surrounding whitespaces.
              </div>
            </div>
            <ToggleSwitch
              checked={config.fix_newlines}
              onChange={(checked) => onUpdateConfig({ fix_newlines: checked })}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
