/**
 * Goal Progress Card Component
 * Enhanced goal tracking with progress visualization,
 * status indicators, and milestone tracking
 * Connects to GET /api/portfolio/goals/:goalId/progress
 */

import React, { useEffect, useState } from 'react';
import {
  FlagIcon,
  CalendarIcon,
  BanknotesIcon,
  ChartBarIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  ClockIcon,
  ArrowTrendingUpIcon,
  SparklesIcon,
} from '@heroicons/react/24/solid';
import {
  getGoalProgress,
  type GoalProgress,
  type GoalMilestone,
} from '../../../services/portfolio.service';

interface GoalProgressCardProps {
  goalId: string;
  compact?: boolean;
  onUpdate?: () => void;
}

interface StatusConfig {
  icon: React.ElementType;
  color: string;
  bgColor: string;
  label: string;
  description: string;
}

const STATUS_CONFIGS: Record<string, StatusConfig> = {
  on_track: {
    icon: CheckCircleIcon,
    color: 'text-green-500',
    bgColor: 'bg-green-100 dark:bg-green-900/30',
    label: 'En Camino',
    description: 'Vas bien para alcanzar tu meta',
  },
  at_risk: {
    icon: ClockIcon,
    color: 'text-yellow-500',
    bgColor: 'bg-yellow-100 dark:bg-yellow-900/30',
    label: 'En Riesgo',
    description: 'Considera aumentar tus aportes',
  },
  behind: {
    icon: ExclamationTriangleIcon,
    color: 'text-red-500',
    bgColor: 'bg-red-100 dark:bg-red-900/30',
    label: 'Atrasado',
    description: 'Necesitas ajustar tu estrategia',
  },
};

interface MilestoneItemProps {
  milestone: GoalMilestone;
  goalAmount: number;
}

const MilestoneItem: React.FC<MilestoneItemProps> = ({ milestone, goalAmount }) => {
  return (
    <div
      className={`flex items-center gap-3 p-2 rounded-lg ${
        milestone.achieved
          ? 'bg-green-50 dark:bg-green-900/20'
          : 'bg-gray-50 dark:bg-gray-700/50'
      }`}
    >
      <div
        className={`p-1.5 rounded-full ${
          milestone.achieved
            ? 'bg-green-100 dark:bg-green-900/40'
            : 'bg-gray-200 dark:bg-gray-600'
        }`}
      >
        {milestone.achieved ? (
          <CheckCircleIcon className="w-4 h-4 text-green-500" />
        ) : (
          <FlagIcon className="w-4 h-4 text-gray-400" />
        )}
      </div>
      <div className="flex-1">
        <p className={`text-sm font-medium ${milestone.achieved ? 'text-green-700 dark:text-green-400' : 'text-gray-700 dark:text-gray-300'}`}>
          {milestone.percent}% - ${milestone.amount.toLocaleString()}
        </p>
        <p className="text-xs text-gray-500 dark:text-gray-400">
          {milestone.achieved
            ? `Alcanzado el ${new Date(milestone.date).toLocaleDateString()}`
            : `Proyectado: ${new Date(milestone.date).toLocaleDateString()}`}
        </p>
      </div>
    </div>
  );
};

export const GoalProgressCard: React.FC<GoalProgressCardProps> = ({
  goalId,
  compact = false,
  onUpdate,
}) => {
  const [progress, setProgress] = useState<GoalProgress | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadProgress();
  }, [goalId]);

  const loadProgress = async () => {
    try {
      setLoading(true);
      setError(null);
      const data = await getGoalProgress(goalId);
      setProgress(data);
    } catch (err) {
      console.error('Error loading goal progress:', err);
      setError(err instanceof Error ? err.message : 'Error al cargar progreso');
      // Use mock data for demo
      setProgress(generateMockProgress(goalId));
    } finally {
      setLoading(false);
    }
  };

  const generateMockProgress = (gId: string): GoalProgress => ({
    goalId: gId,
    name: 'Fondo de Emergencia',
    currentAmount: 7500,
    targetAmount: 15000,
    progress: 50,
    monthlyContribution: 500,
    monthsRemaining: 15,
    projectedCompletion: new Date(Date.now() + 15 * 30 * 24 * 60 * 60 * 1000).toISOString(),
    status: 'on_track',
    requiredMonthlyRate: 500,
    onTrackPercentage: 95,
    milestones: [
      { percent: 25, amount: 3750, date: new Date(Date.now() - 60 * 24 * 60 * 60 * 1000).toISOString(), achieved: true },
      { percent: 50, amount: 7500, date: new Date().toISOString(), achieved: true },
      { percent: 75, amount: 11250, date: new Date(Date.now() + 90 * 24 * 60 * 60 * 1000).toISOString(), achieved: false },
      { percent: 100, amount: 15000, date: new Date(Date.now() + 180 * 24 * 60 * 60 * 1000).toISOString(), achieved: false },
    ],
  });

  if (loading) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
        <div className="flex items-center justify-center py-8">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        </div>
      </div>
    );
  }

  if (!progress) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
        <div className="text-center py-4">
          <ExclamationTriangleIcon className="w-8 h-8 text-yellow-500 mx-auto mb-2" />
          <p className="text-gray-500 dark:text-gray-400">
            {error || 'No se pudo cargar el progreso'}
          </p>
        </div>
      </div>
    );
  }

  const statusConfig = STATUS_CONFIGS[progress.status];
  const StatusIcon = statusConfig.icon;
  const progressPercent = Math.min(100, progress.progress);
  const remaining = progress.targetAmount - progress.currentAmount;

  if (compact) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-4">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2">
            <div className={`p-1.5 rounded-lg ${statusConfig.bgColor}`}>
              <StatusIcon className={`w-4 h-4 ${statusConfig.color}`} />
            </div>
            <h4 className="font-medium text-gray-900 dark:text-white truncate">
              {progress.name}
            </h4>
          </div>
          <span className={`text-sm font-bold ${statusConfig.color}`}>
            {progressPercent.toFixed(0)}%
          </span>
        </div>
        {/* Progress bar */}
        <div className="h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
          <div
            className={`h-full rounded-full transition-all ${
              progress.status === 'on_track'
                ? 'bg-green-500'
                : progress.status === 'at_risk'
                ? 'bg-yellow-500'
                : 'bg-red-500'
            }`}
            style={{ width: `${progressPercent}%` }}
          />
        </div>
        <div className="flex justify-between mt-2 text-xs text-gray-500 dark:text-gray-400">
          <span>${progress.currentAmount.toLocaleString()}</span>
          <span>${progress.targetAmount.toLocaleString()}</span>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
      {/* Header */}
      <div className="flex items-start justify-between mb-6">
        <div className="flex items-center gap-3">
          <div className={`p-3 rounded-lg ${statusConfig.bgColor}`}>
            <FlagIcon className={`w-6 h-6 ${statusConfig.color}`} />
          </div>
          <div>
            <h3 className="font-bold text-gray-900 dark:text-white">
              {progress.name}
            </h3>
            <div className="flex items-center gap-2 mt-1">
              <StatusIcon className={`w-4 h-4 ${statusConfig.color}`} />
              <span className={`text-sm ${statusConfig.color}`}>
                {statusConfig.label}
              </span>
            </div>
          </div>
        </div>
        {progress.status === 'on_track' && progress.onTrackPercentage >= 90 && (
          <div className="flex items-center gap-1 px-2 py-1 bg-green-100 dark:bg-green-900/30 rounded-full">
            <SparklesIcon className="w-4 h-4 text-green-500" />
            <span className="text-xs font-medium text-green-600">Excelente</span>
          </div>
        )}
      </div>

      {/* Main Progress Display */}
      <div className="mb-6">
        <div className="flex items-end justify-between mb-2">
          <div>
            <p className="text-sm text-gray-500 dark:text-gray-400">Progreso Actual</p>
            <p className="text-3xl font-bold text-gray-900 dark:text-white">
              {progressPercent.toFixed(1)}%
            </p>
          </div>
          <div className="text-right">
            <p className="text-sm text-gray-500 dark:text-gray-400">
              ${progress.currentAmount.toLocaleString()}
            </p>
            <p className="text-sm font-medium text-gray-900 dark:text-white">
              de ${progress.targetAmount.toLocaleString()}
            </p>
          </div>
        </div>

        {/* Progress bar with milestones */}
        <div className="relative">
          <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
            <div
              className={`h-full rounded-full transition-all duration-500 ${
                progress.status === 'on_track'
                  ? 'bg-gradient-to-r from-green-400 to-green-500'
                  : progress.status === 'at_risk'
                  ? 'bg-gradient-to-r from-yellow-400 to-yellow-500'
                  : 'bg-gradient-to-r from-red-400 to-red-500'
              }`}
              style={{ width: `${progressPercent}%` }}
            />
          </div>
          {/* Milestone markers */}
          <div className="absolute inset-0 flex justify-between items-center px-1">
            {[25, 50, 75, 100].map((milestone) => (
              <div
                key={milestone}
                className={`w-2 h-2 rounded-full transform -translate-y-0 ${
                  progressPercent >= milestone
                    ? 'bg-white shadow'
                    : 'bg-gray-400 dark:bg-gray-500'
                }`}
                style={{ left: `${milestone}%` }}
              />
            ))}
          </div>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 gap-4 mb-6">
        <div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
          <div className="flex items-center gap-2 mb-1">
            <BanknotesIcon className="w-4 h-4 text-blue-500" />
            <span className="text-xs text-gray-500 dark:text-gray-400">Faltante</span>
          </div>
          <p className="font-bold text-gray-900 dark:text-white">
            ${remaining.toLocaleString()}
          </p>
        </div>
        <div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
          <div className="flex items-center gap-2 mb-1">
            <ChartBarIcon className="w-4 h-4 text-purple-500" />
            <span className="text-xs text-gray-500 dark:text-gray-400">Aporte Mensual</span>
          </div>
          <p className="font-bold text-gray-900 dark:text-white">
            ${progress.monthlyContribution.toLocaleString()}
          </p>
        </div>
        <div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
          <div className="flex items-center gap-2 mb-1">
            <CalendarIcon className="w-4 h-4 text-orange-500" />
            <span className="text-xs text-gray-500 dark:text-gray-400">Meses Restantes</span>
          </div>
          <p className="font-bold text-gray-900 dark:text-white">
            {progress.monthsRemaining}
          </p>
        </div>
        <div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg">
          <div className="flex items-center gap-2 mb-1">
            <ArrowTrendingUpIcon className="w-4 h-4 text-green-500" />
            <span className="text-xs text-gray-500 dark:text-gray-400">Aporte Requerido</span>
          </div>
          <p className={`font-bold ${
            progress.requiredMonthlyRate <= progress.monthlyContribution
              ? 'text-green-500'
              : 'text-red-500'
          }`}>
            ${progress.requiredMonthlyRate.toLocaleString()}
          </p>
        </div>
      </div>

      {/* Projected Completion */}
      {progress.projectedCompletion && (
        <div className="mb-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <CalendarIcon className="w-5 h-5 text-blue-500" />
              <span className="text-sm text-gray-600 dark:text-gray-400">
                Fecha Proyectada de Cumplimiento
              </span>
            </div>
            <span className="font-bold text-blue-600 dark:text-blue-400">
              {new Date(progress.projectedCompletion).toLocaleDateString('es-ES', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
              })}
            </span>
          </div>
        </div>
      )}

      {/* On-Track Indicator */}
      <div className="mb-6">
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm text-gray-500 dark:text-gray-400">
            Probabilidad de Exito
          </span>
          <span className={`font-bold ${
            progress.onTrackPercentage >= 80
              ? 'text-green-500'
              : progress.onTrackPercentage >= 50
              ? 'text-yellow-500'
              : 'text-red-500'
          }`}>
            {progress.onTrackPercentage}%
          </span>
        </div>
        <div className="h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
          <div
            className={`h-full rounded-full ${
              progress.onTrackPercentage >= 80
                ? 'bg-green-500'
                : progress.onTrackPercentage >= 50
                ? 'bg-yellow-500'
                : 'bg-red-500'
            }`}
            style={{ width: `${progress.onTrackPercentage}%` }}
          />
        </div>
      </div>

      {/* Milestones */}
      {progress.milestones && progress.milestones.length > 0 && (
        <div>
          <h4 className="font-semibold text-gray-700 dark:text-gray-300 mb-3">
            Hitos
          </h4>
          <div className="space-y-2">
            {progress.milestones.map((milestone, index) => (
              <MilestoneItem
                key={index}
                milestone={milestone}
                goalAmount={progress.targetAmount}
              />
            ))}
          </div>
        </div>
      )}

      {/* Status Description */}
      <div className="mt-6 pt-4 border-t border-gray-200 dark:border-gray-700">
        <p className="text-sm text-gray-500 dark:text-gray-400">
          {statusConfig.description}
        </p>
      </div>

      {/* Update Button */}
      {onUpdate && (
        <button
          onClick={onUpdate}
          className="mt-4 w-full py-3 bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 font-medium rounded-lg hover:bg-blue-100 dark:hover:bg-blue-900/50 transition-colors"
        >
          Actualizar Progreso
        </button>
      )}
    </div>
  );
};

export default GoalProgressCard;
