import { useCallback, useEffect, useState } from "react";

import { getUserConfig, updateUserConfig, type UserConfig, type UserConfigUpdate } from "../api/settings";
import { Icon } from "../components/icon";

type SettingsStatus = "loading" | "ready" | "error";

const THEME_OPTIONS = [
  { value: "system", label: "System" },
  { value: "light", label: "Light" },
  { value: "dark", label: "Dark" },
];

export const SettingsPage = () => {
  const [status, setStatus] = useState<SettingsStatus>("loading");
  const [config, setConfig] = useState<UserConfig>({
    theme: "system",
    default_editor: null,
    git_user_name: null,
    git_user_email: null,
    last_session_id: null,
  });
  const [saveStatus, setSaveStatus] = useState<"idle" | "saving" | "saved" | "error">("idle");

  const loadConfig = useCallback(async () => {
    try {
      const data = await getUserConfig();
      setConfig(data);
      setStatus("ready");
    } catch {
      setStatus("error");
    }
  }, []);

  useEffect(() => {
    void loadConfig();
  }, [loadConfig]);

  const handleChange = (key: keyof UserConfigUpdate, value: string | null) => {
    setConfig((prev) => ({ ...prev, [key]: value }));
    setSaveStatus("idle");
  };

  const handleSave = async () => {
    setSaveStatus("saving");
    try {
      const update: UserConfigUpdate = {
        theme: config.theme,
        default_editor: config.default_editor,
        git_user_name: config.git_user_name,
        git_user_email: config.git_user_email,
      };
      console.log("Sending update:", update);
      const updated = await updateUserConfig(update);
      console.log("Received response:", updated);
      setConfig(updated);
      setSaveStatus("saved");
      
      // Apply theme immediately
      const theme = updated.theme ?? "system";
      if (theme === "system") {
        document.documentElement.removeAttribute("data-theme");
      } else {
        document.documentElement.setAttribute("data-theme", theme);
      }
      
      setTimeout(() => setSaveStatus("idle"), 2000);
    } catch {
      setSaveStatus("error");
    }
  };

  if (status === "loading") {
    return <section className="stack"><p className="muted">Loading settings...</p></section>;
  }

  if (status === "error") {
    return (
      <section className="stack">
        <p>Failed to load settings</p>
        <button className="secondary-button" onClick={() => void loadConfig()} type="button">
          <Icon name="refresh" size="sm" />
          Retry
        </button>
      </section>
    );
  }

  return (
    <section className="stack">
      <div className="page-header">
        <h1>Settings</h1>
      </div>

      <div className="card stack">
        <h2>Appearance</h2>
        <label className="form-field">
          Theme
          <select
            value={config.theme}
            onChange={(e) => handleChange("theme", e.target.value)}
          >
            {THEME_OPTIONS.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
        </label>
      </div>

      <div className="card stack">
        <h2>Git Identity</h2>
        <label className="form-field">
          User Name
          <input
            type="text"
            value={config.git_user_name ?? ""}
            onChange={(e) => handleChange("git_user_name", e.target.value || null)}
            placeholder="Your git commit name"
          />
        </label>
        <label className="form-field">
          User Email
          <input
            type="email"
            value={config.git_user_email ?? ""}
            onChange={(e) => handleChange("git_user_email", e.target.value || null)}
            placeholder="your.email@example.com"
          />
        </label>
      </div>

      <div className="card stack">
        <h2>Editor</h2>
        <label className="form-field">
          Default Editor
          <input
            type="text"
            value={config.default_editor ?? ""}
            onChange={(e) => handleChange("default_editor", e.target.value || null)}
            placeholder="e.g., vscode, vim, cursor"
          />
        </label>
      </div>

      <div className="settings-actions">
        <button className="primary-button" onClick={() => void handleSave()} type="button">
          {saveStatus === "saving" ? (
            <>
              <Icon name="loading" size="sm" />
              Saving...
            </>
          ) : (
            <>
              <Icon name="save" size="sm" />
              Save Settings
            </>
          )}
        </button>
        {saveStatus === "saved" && <span className="success-text">Settings saved!</span>}
        {saveStatus === "error" && <span className="error-text">Failed to save</span>}
      </div>
    </section>
  );
};
