import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { apiClient } from "../api/client";
import { GitRepository } from "../api/git_repositories";

export const RepositoriesSettingsTab: React.FC = () => {
  const { projectId } = useParams<{ projectId: string }>();
  const [repositories, setRepositories] = useState<GitRepository[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(">");

  useEffect(() => {
    const fetchRepositories = async () => {
      try {
        const response = await apiClient.get(
          `/projects/${projectId}/repositories`
        );
        setRepositories(response.data);
      } catch (err) {
        setError("Failed to load repositories");
      } finally {
        setLoading(false);
      }
    };

    fetchRepositories();
  }, [projectId]);

  const handleDelete = async (repoId: string) => {
    if (!window.confirm("Are you sure you want to delete this repository?")) return;
    try {
      await apiClient.delete(`/projects/${projectId}/repositories/${repoId}`);
      setRepositories(repositories.filter((r) => r.id !== repoId));
    } catch (err) {
      setError("Failed to delete repository");
    }
  };

  if (loading) return <div>Loading...</div>;

  return (
    <div className="repositories-settings-tab">
      <h2>Repositories</h2>
      {error && <div className="error-message">{error}</div>}

      <div className="repositories-list">
        {repositories.length === 0 ? (
          <p>No repositories yet.</p>
        ) : (
          repositories.map((repo) => (
            <div key={repo.id} className="repository-card">
              <div className="repository-info">
                <h3>{repo.name}</h3>
                <p>{repo.remote_url}</p>
                <span className="repo-type">
                  {repo.is_mirror ? "Mirror" : "Clone"}
                </span>
              </div>
              <button
                onClick={() => handleDelete(repo.id)}
                className="btn-danger"
              >
                Delete
              </button>
            </div>
          ))
        )}
      </div>
    </div>
  );
};
