import { useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { listProjectModules, setProjectModuleEnabled } from "../../lib/api";
import { getErrorMessage } from "../../lib/errors";
import type { ProjectModule } from "../../lib/types";
import {
  buttonClass,
  cardContentClass,
  noticeClass,
  pageClass,
  pageTitleClass,
  backLinkClass,
} from "../ui/primitives";

export default function ProjectModules() {
  const { projectId } = useParams<{ projectId: string }>();
  const [modules, setModules] = useState<ProjectModule[]>([]);
  const [savingKey, setSavingKey] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  async function refresh() {
    if (!projectId) return;

    setError(null);
    try {
      const result = await listProjectModules(projectId);
      setModules(result);
    } catch (err: unknown) {
      setError(getErrorMessage(err));
    }
  }

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

  async function handleToggle(moduleKey: string, enabled: boolean) {
    if (!projectId) return;

    setSavingKey(moduleKey);
    setError(null);
    try {
      await setProjectModuleEnabled(projectId, moduleKey, enabled);
      await refresh();
    } catch (err: unknown) {
      setError(getErrorMessage(err));
    } finally {
      setSavingKey(null);
    }
  }

  return (
    <div className={pageClass}>
      <div className="mb-6">
        {projectId && (
          <Link to={`/projects/${projectId}`} className={backLinkClass}>
            Back
          </Link>
        )}
        <h2 className={pageTitleClass}>Modules du projet</h2>
      </div>

      {error && (
        <div className={`mb-4 ${noticeClass("error", true)}`}>
          {error}
        </div>
      )}

      <div className="space-y-3">
        {modules.map((mod) => (
          <div
            key={mod.id}
            className={cardContentClass}
          >
            <div className="flex items-start justify-between gap-4">
              <div>
                <div className="text-sm font-semibold text-gray-900">{mod.name}</div>
                <div className="mt-1 text-xs text-gray-500">{mod.description}</div>
                <div className="mt-2 font-mono text-[11px] text-gray-400">{mod.module_key}</div>
                {projectId && mod.module_key === "graylog_polling_auto_resolve" && (
                  <Link
                    to={`/projects/${projectId}/graylog`}
                    className={`mt-2 ${buttonClass({ variant: "secondary", size: "xs" })}`}
                  >
                    Configurer
                  </Link>
                )}
              </div>
              <label className="inline-flex items-center gap-2 text-sm text-gray-700">
                <input
                  type="checkbox"
                  checked={mod.enabled}
                  disabled={savingKey === mod.module_key}
                  onChange={(e) => void handleToggle(mod.module_key, e.target.checked)}
                />
                {mod.enabled ? "Activé" : "Désactivé"}
              </label>
            </div>
          </div>
        ))}
      </div>

      {modules.length === 0 && (
        <div className="text-sm text-gray-400">Aucun module disponible.</div>
      )}
    </div>
  );
}
