import React, { useState } from 'react';
import {
  ExternalLink,
  RefreshCw,
  Rocket,
  Clock,
  GitBranch,
  Activity,
  ChevronDown,
  ChevronUp,
  Terminal,
  AlertTriangle,
  Play,
  Square,
  RotateCcw,
} from 'lucide-react';
import StatusBadge from './StatusBadge';
import { deployApp, checkApp, getAppLogs, startApp, stopApp, restartApp } from '../utils/api';

function formatDate(dateStr) {
  if (!dateStr) return 'N/A';
  try {
    const date = new Date(dateStr);
    return date.toLocaleString('fr-FR', {
      day: '2-digit',
      month: '2-digit',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  } catch {
    return dateStr;
  }
}

function formatResponseTime(ms) {
  if (!ms) return 'N/A';
  if (ms < 1000) return `${ms}ms`;
  return `${(ms / 1000).toFixed(1)}s`;
}

export default function AppCard({ app, commits, onRefresh }) {
  const [deploying, setDeploying] = useState(false);
  const [checking, setChecking] = useState(false);
  const [showLogs, setShowLogs] = useState(false);
  const [containerLogs, setContainerLogs] = useState('');
  const [loadingLogs, setLoadingLogs] = useState(false);
  const [deployMessage, setDeployMessage] = useState(null);
  const [loadingControl, setLoadingControl] = useState(null);

  const handleContainerControl = async (action) => {
    setLoadingControl(action);
    try {
      if (action === 'start') await startApp(app.id);
      else if (action === 'stop') await stopApp(app.id);
      else if (action === 'restart') await restartApp(app.id);
      setTimeout(() => { if (onRefresh) onRefresh(); }, 2000);
    } catch (err) {
      console.error('Erreur controle conteneur:', err);
    } finally {
      setLoadingControl(null);
    }
  };

  const handleDeploy = async () => {
    if (!confirm(`Voulez-vous redéployer ${app.name} ?`)) return;
    setDeploying(true);
    setDeployMessage(null);
    try {
      const res = await deployApp(app.id);
      setDeployMessage({
        type: 'info',
        text: res.data.message || 'Redéploiement lancé...',
      });
      // Rafraîchir après un délai
      setTimeout(() => {
        if (onRefresh) onRefresh();
        setDeploying(false);
      }, 10000);
    } catch (err) {
      setDeployMessage({
        type: 'error',
        text: err.response?.data?.error || 'Erreur lors du redéploiement',
      });
      setDeploying(false);
    }
  };

  const handleCheck = async () => {
    setChecking(true);
    try {
      await checkApp(app.id);
      if (onRefresh) onRefresh();
    } catch (err) {
      console.error('Erreur health check:', err);
    } finally {
      setChecking(false);
    }
  };

  const handleShowLogs = async () => {
    if (showLogs) {
      setShowLogs(false);
      return;
    }
    setLoadingLogs(true);
    setShowLogs(true);
    try {
      const res = await getAppLogs(app.id, 50);
      setContainerLogs(res.data.logs || 'Aucun log disponible');
    } catch (err) {
      setContainerLogs('Erreur lors de la récupération des logs');
    } finally {
      setLoadingLogs(false);
    }
  };

  const latestCommit = commits && commits.length > 0 ? commits[0] : null;

  // Apps d'infrastructure : portail et dashboard
  const isInfra = ['portail-santinova', 'manus-dashboard'].includes(app.id);

  return (
    <div className={`card overflow-hidden${isInfra ? ' border border-amber-500/30 bg-amber-950/10' : ''}`}>
      {/* Badge infra */}
      {isInfra && (
        <div className="px-6 pt-3 pb-0">
          <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold bg-amber-500/15 text-amber-400 border border-amber-500/30">
            ⚙ Infrastructure
          </span>
        </div>
      )}
      {/* Header */}
      <div className="p-6 border-b border-dark-700">
        <div className="flex items-start justify-between">
          <div className="flex-1">
            <div className="flex items-center gap-3">
              <h3 className="text-lg font-semibold text-white">{app.name}</h3>
              <StatusBadge status={app.status} />
            </div>
            <p className="text-gray-400 text-sm mt-1">
              {app.description || app.id}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <button
              onClick={handleCheck}
              disabled={checking}
              className="btn-secondary py-1.5 px-3 text-sm flex items-center gap-1.5"
              title="Vérifier l'état"
            >
              <RefreshCw
                className={`w-3.5 h-3.5 ${checking ? 'animate-spin' : ''}`}
              />
              Vérifier
            </button>
            <button
              onClick={handleDeploy}
              disabled={deploying}
              className="btn-primary py-1.5 px-3 text-sm flex items-center gap-1.5"
              title="Redéployer l'application"
            >
              <Rocket
                className={`w-3.5 h-3.5 ${deploying ? 'animate-bounce' : ''}`}
              />
              {deploying ? 'Déploiement...' : 'Redéployer'}
            </button>
            {/* Boutons contrôle conteneur */}
            <div className="flex items-center gap-1 ml-1 border-l border-dark-600 pl-2">
              <button
                onClick={() => handleContainerControl('start')}
                disabled={loadingControl !== null || app.container?.state === 'running'}
                title="Démarrer le conteneur"
                className="p-1.5 rounded-lg text-emerald-400 hover:bg-emerald-500/10 border border-emerald-500/20 disabled:opacity-40 disabled:cursor-not-allowed transition-all"
              >
                {loadingControl === 'start' ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Play className="w-3.5 h-3.5" />}
              </button>
              <button
                onClick={() => handleContainerControl('stop')}
                disabled={loadingControl !== null || app.container?.state !== 'running'}
                title="Arrêter le conteneur"
                className="p-1.5 rounded-lg text-red-400 hover:bg-red-500/10 border border-red-500/20 disabled:opacity-40 disabled:cursor-not-allowed transition-all"
              >
                {loadingControl === 'stop' ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <Square className="w-3.5 h-3.5" />}
              </button>
              <button
                onClick={() => handleContainerControl('restart')}
                disabled={loadingControl !== null}
                title="Redémarrer le conteneur"
                className="p-1.5 rounded-lg text-amber-400 hover:bg-amber-500/10 border border-amber-500/20 disabled:opacity-40 disabled:cursor-not-allowed transition-all"
              >
                {loadingControl === 'restart' ? <RefreshCw className="w-3.5 h-3.5 animate-spin" /> : <RotateCcw className="w-3.5 h-3.5" />}
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Deploy message */}
      {deployMessage && (
        <div
          className={`px-6 py-3 text-sm flex items-center gap-2 ${
            deployMessage.type === 'error'
              ? 'bg-red-500/10 text-red-400'
              : 'bg-primary-500/10 text-primary-400'
          }`}
        >
          {deployMessage.type === 'error' ? (
            <AlertTriangle className="w-4 h-4" />
          ) : (
            <Rocket className="w-4 h-4" />
          )}
          {deployMessage.text}
        </div>
      )}

      {/* Info Grid */}
      <div className="p-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {/* URLs */}
        <div>
          <span className="text-xs font-medium text-gray-500 uppercase tracking-wider">
            URLs
          </span>
          <div className="mt-1.5 space-y-1">
            {app.urls?.recette && (
              <a
                href={app.urls.recette}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-1.5 text-sm text-primary-400 hover:text-primary-300 transition-colors"
              >
                <ExternalLink className="w-3.5 h-3.5" />
                Recette
              </a>
            )}
            {app.urls?.prod ? (
              <a
                href={app.urls.prod}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center gap-1.5 text-sm text-emerald-400 hover:text-emerald-300 transition-colors"
              >
                <ExternalLink className="w-3.5 h-3.5" />
                Production
              </a>
            ) : (
              <span className="text-sm text-gray-600">Pas de prod</span>
            )}
          </div>
        </div>

        {/* Container */}
        <div>
          <span className="text-xs font-medium text-gray-500 uppercase tracking-wider">
            Conteneur
          </span>
          <div className="mt-1.5">
            {app.container ? (
              <div className="space-y-1">
                <p className="text-sm text-gray-300">
                  <span className="text-gray-500">ID:</span>{' '}
                  <code className="text-xs bg-dark-700 px-1.5 py-0.5 rounded">
                    {app.container.id}
                  </code>
                </p>
                <p className="text-sm text-gray-300">
                  <span className="text-gray-500">État:</span>{' '}
                  {app.container.state}
                </p>
              </div>
            ) : (
              <p className="text-sm text-gray-600">Non trouvé</p>
            )}
          </div>
        </div>

        {/* Health */}
        <div>
          <span className="text-xs font-medium text-gray-500 uppercase tracking-wider">
            Santé
          </span>
          <div className="mt-1.5 space-y-1">
            {app.health?.recette && (
              <div className="flex items-center gap-2">
                <Activity
                  className={`w-3.5 h-3.5 ${
                    app.health.recette.online
                      ? 'text-emerald-400'
                      : 'text-red-400'
                  }`}
                />
                <span className="text-sm text-gray-300">
                  {app.health.recette.online ? (
                    <>
                      HTTP {app.health.recette.statusCode} &mdash;{' '}
                      {formatResponseTime(app.health.recette.responseTime)}
                    </>
                  ) : (
                    <span className="text-red-400">
                      {app.health.recette.error || 'Inaccessible'}
                    </span>
                  )}
                </span>
              </div>
            )}
            <p className="text-xs text-gray-600">
              <Clock className="w-3 h-3 inline mr-1" />
              {formatDate(app.lastCheck)}
            </p>
          </div>
        </div>
      </div>

      {/* Latest Commit */}
      {latestCommit && (
        <div className="px-6 py-3 border-t border-dark-700 bg-dark-800/50">
          <div className="flex items-center gap-2">
            <GitBranch className="w-4 h-4 text-gray-500" />
            <span className="text-xs font-medium text-gray-500 uppercase tracking-wider">
              Dernier commit
            </span>
          </div>
          <div className="mt-1.5 flex items-center gap-3">
            <code className="text-xs bg-primary-500/10 text-primary-400 px-2 py-0.5 rounded font-mono">
              {latestCommit.shortSha}
            </code>
            <span className="text-sm text-gray-300 truncate flex-1">
              {latestCommit.message}
            </span>
            <span className="text-xs text-gray-500 flex-shrink-0">
              {latestCommit.author} &mdash; {formatDate(latestCommit.date)}
            </span>
          </div>
        </div>
      )}

      {/* Logs Toggle */}
      <div className="border-t border-dark-700">
        <button
          onClick={handleShowLogs}
          className="w-full px-6 py-3 flex items-center justify-between text-sm text-gray-400 hover:text-gray-300 hover:bg-dark-700/50 transition-colors"
        >
          <span className="flex items-center gap-2">
            <Terminal className="w-4 h-4" />
            Logs du conteneur
          </span>
          {showLogs ? (
            <ChevronUp className="w-4 h-4" />
          ) : (
            <ChevronDown className="w-4 h-4" />
          )}
        </button>
        {showLogs && (
          <div className="px-6 pb-4">
            <div className="bg-dark-950 rounded-lg p-4 max-h-64 overflow-auto">
              {loadingLogs ? (
                <div className="flex items-center gap-2 text-gray-500">
                  <RefreshCw className="w-4 h-4 animate-spin" />
                  Chargement des logs...
                </div>
              ) : (
                <pre className="log-viewer text-xs text-gray-400">
                  {containerLogs}
                </pre>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
