import { useState, useEffect } from "react";
import {
  getTuleapCredentials,
  setTuleapCredentials,
  deleteTuleapCredentials,
  testTuleapConnection,
} from "../../lib/api";
import { getErrorMessage } from "../../lib/errors";
import type { TuleapCredentialsSafe } from "../../lib/types";
import ConfirmModal from "../ui/ConfirmModal";

export default function SettingsPage() {
  const [tuleapUrl, setTuleapUrl] = useState("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [existing, setExisting] = useState<TuleapCredentialsSafe | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);
  const [testing, setTesting] = useState(false);
  const [deleting, setDeleting] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);

  useEffect(() => {
    getTuleapCredentials().then((creds) => {
      if (creds) {
        setExisting(creds);
        setTuleapUrl(creds.tuleap_url);
        setUsername(creds.username);
      }
    });
  }, []);

  function clearMessages() {
    setError(null);
    setSuccess(null);
  }

  async function handleSave(e: React.FormEvent) {
    e.preventDefault();
    clearMessages();
    setSaving(true);
    try {
      const creds = await setTuleapCredentials(tuleapUrl, username, password);
      setExisting(creds);
      setPassword("");
      setSuccess("Credentials saved.");
    } catch (err: unknown) {
      setError(getErrorMessage(err));
    } finally {
      setSaving(false);
    }
  }

  async function handleTest() {
    clearMessages();
    setTesting(true);
    try {
      const msg = await testTuleapConnection();
      setSuccess(msg);
    } catch (err: unknown) {
      setError(getErrorMessage(err));
    } finally {
      setTesting(false);
    }
  }

  async function handleDelete() {
    setIsDeleteModalOpen(false);
    clearMessages();
    setDeleting(true);
    try {
      await deleteTuleapCredentials();
      setExisting(null);
      setTuleapUrl("");
      setUsername("");
      setPassword("");
      setSuccess("Credentials deleted.");
    } catch (err: unknown) {
      setError(getErrorMessage(err));
    } finally {
      setDeleting(false);
    }
  }

  return (
    <div className="max-w-lg mx-auto p-8">
      <h2 className="text-xl font-bold mb-6">Settings</h2>

      <div className="bg-white rounded-lg border border-gray-200 p-6">
        <h3 className="text-base font-semibold mb-4">Tuleap credentials</h3>

        <form onSubmit={handleSave} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Tuleap URL
            </label>
            <input
              type="url"
              value={tuleapUrl}
              onChange={(e) => setTuleapUrl(e.target.value)}
              required
              placeholder="https://tuleap.example.com"
              className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Username
            </label>
            <input
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              required
              className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              Password
            </label>
            <input
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder={existing ? "Leave empty to keep current" : ""}
              className="w-full border border-gray-300 rounded px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {error && (
            <div className="text-red-600 text-sm bg-red-50 border border-red-200 rounded p-2">
              {error}
            </div>
          )}

          {success && (
            <div className="text-green-700 text-sm bg-green-50 border border-green-200 rounded p-2">
              {success}
            </div>
          )}

          <div className="flex gap-2 flex-wrap">
            <button
              type="submit"
              disabled={saving}
              className="px-4 py-2 bg-blue-600 text-white rounded text-sm hover:bg-blue-700 disabled:opacity-50"
            >
              {saving ? "Saving..." : "Save"}
            </button>
            <button
              type="button"
              onClick={handleTest}
              disabled={testing || !existing}
              className="px-4 py-2 bg-gray-200 rounded text-sm hover:bg-gray-300 disabled:opacity-50"
            >
              {testing ? "Testing..." : "Test connection"}
            </button>
            {existing && (
              <button
                type="button"
                onClick={() => setIsDeleteModalOpen(true)}
                disabled={deleting}
                className="px-4 py-2 bg-red-600 text-white rounded text-sm hover:bg-red-700 disabled:opacity-50"
              >
                {deleting ? "Deleting..." : "Delete"}
              </button>
            )}
          </div>
        </form>
      </div>

      <ConfirmModal
        isOpen={isDeleteModalOpen}
        confirmDisabled={deleting}
        onCancel={() => setIsDeleteModalOpen(false)}
        onConfirm={() => void handleDelete()}
      />
    </div>
  );
}
