'use client';

import { Card, CardHeader, CardContent } from '@/components/ui/Card';
import { SprintDetails } from '../SprintDetailModal';
import { Emoji } from '@/components/ui/Emoji';

interface SprintMetricsProps {
  sprintDetails: SprintDetails;
}

export function SprintMetrics({ sprintDetails }: SprintMetricsProps) {
  const { sprint, metrics, assigneeDistribution } = sprintDetails;

  const completionRate =
    metrics.totalIssues > 0
      ? ((metrics.completedIssues / metrics.totalIssues) * 100).toFixed(1)
      : '0';

  const inProgressRate =
    metrics.totalIssues > 0
      ? ((metrics.inProgressIssues / metrics.totalIssues) * 100).toFixed(1)
      : '0';

  const blockedRate =
    metrics.totalIssues > 0
      ? ((metrics.blockedIssues / metrics.totalIssues) * 100).toFixed(1)
      : '0';

  const getVelocityTrendColor = (trend: string) => {
    switch (trend) {
      case 'up':
        return 'text-green-600';
      case 'down':
        return 'text-red-600';
      case 'stable':
        return 'text-blue-600';
      default:
        return 'text-gray-600';
    }
  };

  const getVelocityTrendIcon = (trend: string) => {
    switch (trend) {
      case 'up':
        return <Emoji emoji="📈" />;
      case 'down':
        return <Emoji emoji="📉" />;
      case 'stable':
        return <Emoji emoji="➡️" />;
      default:
        return <Emoji emoji="📊" />;
    }
  };

  return (
    <div className="space-y-4">
      {/* Métriques de performance */}
      <Card>
        <CardHeader>
          <h3 className="font-semibold">
            <Emoji emoji="⚡" /> Métriques de performance
          </h3>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="text-center p-4 bg-green-50 rounded-lg">
              <div className="text-3xl font-bold text-green-600">
                {completionRate}%
              </div>
              <div className="text-sm text-green-600">Taux de completion</div>
            </div>
            <div className="text-center p-4 bg-blue-50 rounded-lg">
              <div className="text-3xl font-bold text-blue-600">
                {sprint.velocity || sprint.completedPoints}
              </div>
              <div className="text-sm text-blue-600">Vélocité (points)</div>
            </div>
            <div className="text-center p-4 bg-orange-50 rounded-lg">
              <div className="text-3xl font-bold text-orange-600">
                {metrics.averageCycleTime.toFixed(1)}
              </div>
              <div className="text-sm text-orange-600">
                Cycle time moyen (jours)
              </div>
            </div>
            <div className="text-center p-4 bg-purple-50 rounded-lg">
              <div
                className={`text-3xl font-bold ${getVelocityTrendColor(metrics.velocityTrend)}`}
              >
                {getVelocityTrendIcon(metrics.velocityTrend)}
              </div>
              <div
                className={`text-sm ${getVelocityTrendColor(metrics.velocityTrend)}`}
              >
                Tendance vélocité
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Répartition détaillée */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* Répartition par statut avec pourcentages */}
        <Card>
          <CardHeader>
            <h3 className="font-semibold">
              <Emoji emoji="📊" /> Analyse des statuts
            </h3>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="flex items-center justify-between p-3 bg-green-50 rounded">
                <div>
                  <div className="font-medium text-green-800">
                    Issues terminées
                  </div>
                  <div className="text-sm text-green-600">
                    {metrics.completedIssues} issues
                  </div>
                </div>
                <div className="text-2xl font-bold text-green-600">
                  {completionRate}%
                </div>
              </div>

              <div className="flex items-center justify-between p-3 bg-blue-50 rounded">
                <div>
                  <div className="font-medium text-blue-800">
                    Issues en cours
                  </div>
                  <div className="text-sm text-blue-600">
                    {metrics.inProgressIssues} issues
                  </div>
                </div>
                <div className="text-2xl font-bold text-blue-600">
                  {inProgressRate}%
                </div>
              </div>

              <div className="flex items-center justify-between p-3 bg-red-50 rounded">
                <div>
                  <div className="font-medium text-red-800">
                    Issues bloquées
                  </div>
                  <div className="text-sm text-red-600">
                    {metrics.blockedIssues} issues
                  </div>
                </div>
                <div className="text-2xl font-bold text-red-600">
                  {blockedRate}%
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Charge de travail par assigné */}
        <Card>
          <CardHeader>
            <h3 className="font-semibold">
              <Emoji emoji="👥" /> Charge de travail
            </h3>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {assigneeDistribution
                .sort(
                  (a, b) =>
                    (b.count || b.totalIssues) - (a.count || a.totalIssues)
                )
                .map((assignee, index) => {
                  const issueCount = assignee.count || assignee.totalIssues;
                  const percentage =
                    metrics.totalIssues > 0
                      ? ((issueCount / metrics.totalIssues) * 100).toFixed(1)
                      : '0';

                  return (
                    <div
                      key={index}
                      className="flex items-center justify-between p-2 bg-gray-50 rounded"
                    >
                      <div className="flex-1">
                        <div className="font-medium text-sm">
                          {assignee.assignee || 'Non assigné'}
                        </div>
                        <div className="text-xs text-gray-600">
                          {issueCount} issues ({percentage}%)
                        </div>
                      </div>
                      <div className="w-16 bg-gray-200 rounded-full h-2">
                        <div
                          className="bg-blue-500 h-2 rounded-full transition-all duration-300"
                          style={{ width: `${percentage}%` }}
                        />
                      </div>
                    </div>
                  );
                })}
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Insights et recommandations */}
      <Card>
        <CardHeader>
          <h3 className="font-semibold">
            <Emoji emoji="💡" /> Insights & Recommandations
          </h3>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {/* Analyse du taux de completion */}
            {parseFloat(completionRate) >= 80 && (
              <div className="p-3 bg-green-50 border border-green-200 rounded">
                <div className="flex items-center gap-2 mb-1">
                  <Emoji emoji="✅" />
                  <span className="font-medium text-green-800">
                    Excellent taux de completion
                  </span>
                </div>
                <p className="text-sm text-green-700">
                  Le sprint affiche un taux de completion de {completionRate}%,
                  ce qui indique une bonne planification et exécution.
                </p>
              </div>
            )}

            {parseFloat(completionRate) < 60 && (
              <div className="p-3 bg-orange-50 border border-orange-200 rounded">
                <div className="flex items-center gap-2 mb-1">
                  <Emoji emoji="⚠️" />
                  <span className="font-medium text-orange-800">
                    Taux de completion faible
                  </span>
                </div>
                <p className="text-sm text-orange-700">
                  Le taux de completion de {completionRate}% suggère une
                  possible sur-planification ou des blocages.
                </p>
              </div>
            )}

            {/* Analyse des blocages */}
            {parseFloat(blockedRate) > 20 && (
              <div className="p-3 bg-red-50 border border-red-200 rounded">
                <div className="flex items-center gap-2 mb-1">
                  <Emoji emoji="🚨" />
                  <span className="font-medium text-red-800">
                    Trop d&apos;issues bloquées
                  </span>
                </div>
                <p className="text-sm text-red-700">
                  {blockedRate}% des issues sont bloquées. Identifiez et
                  résolvez les blocages pour améliorer le flow.
                </p>
              </div>
            )}

            {/* Analyse de la charge de travail */}
            {assigneeDistribution.length > 0 && (
              <div className="p-3 bg-blue-50 border border-blue-200 rounded">
                <div className="flex items-center gap-2 mb-1">
                  <Emoji emoji="📊" />
                  <span className="font-medium text-blue-800">
                    Répartition de la charge
                  </span>
                </div>
                <p className="text-sm text-blue-700">
                  La charge est répartie entre {assigneeDistribution.length}{' '}
                  assigné(s). Vérifiez l&apos;équilibrage pour optimiser la
                  vélocité d&apos;équipe.
                </p>
              </div>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
