import React, { useState, useEffect } from 'react';
import {
  GitBranch,
  RefreshCw,
  ExternalLink,
  Lock,
  Unlock,
  GitCommit,
  Clock,
  User,
  Code,
} from 'lucide-react';
import { getGiteaRepos, getGiteaCommits } from '../utils/api';

function formatDate(dateStr) {
  if (!dateStr) return 'N/A';
  try {
    return new Date(dateStr).toLocaleString('fr-FR');
  } catch {
    return dateStr;
  }
}

function formatSize(kb) {
  if (!kb) return 'N/A';
  if (kb < 1024) return `${kb} KB`;
  return `${(kb / 1024).toFixed(1)} MB`;
}

export default function GiteaPage() {
  const [repos, setRepos] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedRepo, setSelectedRepo] = useState(null);
  const [commits, setCommits] = useState([]);
  const [loadingCommits, setLoadingCommits] = useState(false);

  const fetchRepos = async () => {
    setLoading(true);
    try {
      const res = await getGiteaRepos();
      setRepos(res.data);
    } catch (err) {
      console.error('Erreur chargement repos:', err);
    } finally {
      setLoading(false);
    }
  };

  const fetchCommits = async (fullName) => {
    setLoadingCommits(true);
    setSelectedRepo(fullName);
    try {
      const [owner, repo] = fullName.split('/');
      const res = await getGiteaCommits(owner, repo);
      setCommits(res.data);
    } catch (err) {
      console.error('Erreur chargement commits:', err);
      setCommits([]);
    } finally {
      setLoadingCommits(false);
    }
  };

  useEffect(() => {
    fetchRepos();
  }, []);

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-white flex items-center gap-3">
            <GitBranch className="w-7 h-7 text-primary-400" />
            Dépôts Gitea
          </h2>
          <p className="text-gray-400 mt-1">
            Explorez les dépôts sur{' '}
            <a
              href="https://git.santinova-soft.org"
              target="_blank"
              rel="noopener noreferrer"
              className="text-primary-400 hover:text-primary-300"
            >
              git.santinova-soft.org
            </a>
          </p>
        </div>
        <button
          onClick={fetchRepos}
          className="btn-secondary flex items-center gap-2"
        >
          <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
          Rafraîchir
        </button>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Repos List */}
        <div className="space-y-3">
          <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">
            Dépôts ({repos.length})
          </h3>
          {loading ? (
            <div className="card p-8 text-center">
              <RefreshCw className="w-6 h-6 text-gray-600 mx-auto animate-spin" />
            </div>
          ) : repos.length === 0 ? (
            <div className="card p-8 text-center">
              <GitBranch className="w-10 h-10 text-gray-600 mx-auto mb-3" />
              <p className="text-gray-400">Aucun dépôt trouvé</p>
            </div>
          ) : (
            repos.map((repo) => (
              <div
                key={repo.id}
                className={`card p-4 cursor-pointer transition-all ${
                  selectedRepo === repo.fullName
                    ? 'border-primary-500/50 bg-primary-500/5'
                    : 'hover:border-dark-600'
                }`}
                onClick={() => fetchCommits(repo.fullName)}
              >
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center gap-2">
                      <Code className="w-4 h-4 text-primary-400" />
                      <h4 className="text-sm font-semibold text-white">
                        {repo.name}
                      </h4>
                      {repo.private ? (
                        <Lock className="w-3 h-3 text-gray-500" />
                      ) : (
                        <Unlock className="w-3 h-3 text-gray-500" />
                      )}
                    </div>
                    <p className="text-xs text-gray-500 mt-1">
                      {repo.description || 'Pas de description'}
                    </p>
                    <div className="flex items-center gap-4 mt-2">
                      {repo.language && (
                        <span className="text-xs text-gray-400">
                          {repo.language}
                        </span>
                      )}
                      <span className="text-xs text-gray-500">
                        {formatSize(repo.size)}
                      </span>
                      <span className="text-xs text-gray-500">
                        Mis à jour: {formatDate(repo.updatedAt)}
                      </span>
                    </div>
                  </div>
                  <a
                    href={repo.htmlUrl}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-gray-500 hover:text-primary-400 transition-colors"
                    onClick={(e) => e.stopPropagation()}
                  >
                    <ExternalLink className="w-4 h-4" />
                  </a>
                </div>
              </div>
            ))
          )}
        </div>

        {/* Commits */}
        <div className="space-y-3">
          <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider">
            {selectedRepo
              ? `Commits — ${selectedRepo}`
              : 'Sélectionnez un dépôt'}
          </h3>
          {!selectedRepo ? (
            <div className="card p-8 text-center">
              <GitCommit className="w-10 h-10 text-gray-600 mx-auto mb-3" />
              <p className="text-gray-400 text-sm">
                Cliquez sur un dépôt pour voir ses commits
              </p>
            </div>
          ) : loadingCommits ? (
            <div className="card p-8 text-center">
              <RefreshCw className="w-6 h-6 text-gray-600 mx-auto animate-spin" />
            </div>
          ) : commits.length === 0 ? (
            <div className="card p-8 text-center">
              <GitCommit className="w-10 h-10 text-gray-600 mx-auto mb-3" />
              <p className="text-gray-400">Aucun commit trouvé</p>
            </div>
          ) : (
            <div className="space-y-2">
              {commits.map((commit, idx) => (
                <div key={commit.sha || idx} className="card p-3">
                  <div className="flex items-start gap-3">
                    <div className="mt-1">
                      <GitCommit className="w-4 h-4 text-gray-500" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm text-gray-200 truncate">
                        {commit.message}
                      </p>
                      <div className="flex items-center gap-3 mt-1">
                        <code className="text-xs bg-dark-700 text-primary-400 px-1.5 py-0.5 rounded font-mono">
                          {commit.shortSha}
                        </code>
                        <span className="text-xs text-gray-500 flex items-center gap-1">
                          <User className="w-3 h-3" />
                          {commit.author}
                        </span>
                        <span className="text-xs text-gray-500 flex items-center gap-1">
                          <Clock className="w-3 h-3" />
                          {formatDate(commit.date)}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
