import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { open } from "@tauri-apps/plugin-dialog";
import { createProject, getProject, updateProject } from "../../lib/api";
import { getErrorMessage } from "../../lib/errors";
import {
  buttonClass,
  inputClass,
  labelClass,
  noticeClass,
  pageTitleClass,
} from "../ui/primitives";

export default function ProjectForm() {
  const navigate = useNavigate();
  const { projectId } = useParams();
  const isEditing = Boolean(projectId);

  const [name, setName] = useState("");
  const [pathOrUrl, setPathOrUrl] = useState("");
  const [baseBranch, setBaseBranch] = useState("main");
  const [mode, setMode] = useState<"local" | "clone">("local");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (projectId) {
      getProject(projectId).then((project) => {
        setName(project.name);
        setPathOrUrl(project.path);
        setBaseBranch(project.base_branch);
        if (project.cloned_from) {
          setMode("clone");
        }
      });
    }
  }, [projectId]);

  async function handleBrowse() {
    const selected = await open({ directory: true, multiple: false });
    if (selected) {
      setPathOrUrl(selected as string);
    }
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      if (isEditing && projectId) {
        await updateProject(projectId, name, baseBranch);
        window.dispatchEvent(new Event("orchai:refresh-projects"));
        navigate(`/projects/${projectId}`);
      } else {
        const project = await createProject(name, pathOrUrl, baseBranch);
        window.dispatchEvent(new Event("orchai:refresh-projects"));
        navigate(`/projects/${project.id}`);
      }
    } catch (err: unknown) {
      setError(getErrorMessage(err));
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="max-w-lg mx-auto p-8">
      <h2 className={`${pageTitleClass} mb-6`}>
        {isEditing ? "Edit project" : "New project"}
      </h2>

      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label className={labelClass}>
            Project name
          </label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
            className={inputClass}
          />
        </div>

        {!isEditing && (
          <>
            <div>
              <label className={labelClass}>
                Source
              </label>
              <div className="flex gap-4">
                <label className="flex items-center gap-1 text-sm">
                  <input
                    type="radio"
                    checked={mode === "local"}
                    onChange={() => setMode("local")}
                  />
                  Local folder
                </label>
                <label className="flex items-center gap-1 text-sm">
                  <input
                    type="radio"
                    checked={mode === "clone"}
                    onChange={() => setMode("clone")}
                  />
                  Clone from URL
                </label>
              </div>
            </div>

            <div>
              <label className={labelClass}>
                {mode === "local" ? "Folder path" : "Git URL"}
              </label>
              <div className="flex gap-2">
                <input
                  type="text"
                  value={pathOrUrl}
                  onChange={(e) => setPathOrUrl(e.target.value)}
                  required
                  placeholder={
                    mode === "local"
                      ? "/home/user/code/myproject"
                      : "https://github.com/org/repo.git"
                  }
                  className={`flex-1 ${inputClass}`}
                />
                {mode === "local" && (
                  <button
                    type="button"
                    onClick={handleBrowse}
                    className={buttonClass({ variant: "secondary" })}
                  >
                    Browse
                  </button>
                )}
              </div>
            </div>
          </>
        )}

        <div>
          <label className={labelClass}>
            Base branch
          </label>
          <input
            type="text"
            value={baseBranch}
            onChange={(e) => setBaseBranch(e.target.value)}
            required
            className={inputClass}
          />
        </div>

        {error && (
          <div className={noticeClass("error", true)}>
            {error}
          </div>
        )}

        <div className="flex gap-2">
          <button
            type="submit"
            disabled={loading}
            className={buttonClass({ variant: "primary" })}
          >
            {loading ? "Saving..." : isEditing ? "Save" : "Create"}
          </button>
          <button
            type="button"
            onClick={() => navigate(-1)}
            className={buttonClass({ variant: "secondary" })}
          >
            Cancel
          </button>
        </div>
      </form>
    </div>
  );
}
