import { useEffect, useState } from "react";
import { useParams, Link, useNavigate } from "react-router-dom";
import { getProject, deleteProject } from "../../lib/api";
import type { Project } from "../../lib/types";

export default function ProjectDashboard() {
  const { projectId } = useParams();
  const navigate = useNavigate();
  const [project, setProject] = useState<Project | null>(null);

  useEffect(() => {
    if (projectId) {
      getProject(projectId).then(setProject);
    }
  }, [projectId]);

  async function handleDelete() {
    if (!projectId) return;
    if (!window.confirm(`Delete project "${project?.name}"?`)) return;

    await deleteProject(projectId);
    window.dispatchEvent(new Event("orchai:refresh-projects"));
    navigate("/");
  }

  if (!project) {
    return <div className="p-8 text-gray-400">Loading...</div>;
  }

  return (
    <div className="p-8">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-xl font-bold">{project.name}</h2>
        <div className="flex gap-2">
          <Link
            to={`/projects/${project.id}/edit`}
            className="px-3 py-1 bg-gray-200 rounded text-sm hover:bg-gray-300"
          >
            Edit
          </Link>
          <button
            onClick={handleDelete}
            className="px-3 py-1 bg-red-100 text-red-700 rounded text-sm hover:bg-red-200"
          >
            Delete
          </button>
        </div>
      </div>

      <div className="bg-white rounded-lg border border-gray-200 p-4 space-y-3">
        <div>
          <span className="text-sm text-gray-500">Path:</span>
          <span className="ml-2 text-sm font-mono">{project.path}</span>
        </div>
        {project.cloned_from && (
          <div>
            <span className="text-sm text-gray-500">Cloned from:</span>
            <span className="ml-2 text-sm font-mono">{project.cloned_from}</span>
          </div>
        )}
        <div>
          <span className="text-sm text-gray-500">Base branch:</span>
          <span className="ml-2 text-sm font-mono">{project.base_branch}</span>
        </div>
        <div>
          <span className="text-sm text-gray-500">Created:</span>
          <span className="ml-2 text-sm">{new Date(project.created_at).toLocaleDateString()}</span>
        </div>
      </div>

      <div className="mt-8 text-gray-400 text-sm">
        Tracker surveillance and ticket processing will be available in the next update.
      </div>
    </div>
  );
}
