/**
 * Goals Manager Component
 * Comprehensive goal management with CRUD operations,
 * progress tracking, required savings rate calculator,
 * and goal timeline visualization
 */

import React, { useState, useEffect, useMemo } from 'react';
import { Link } from 'react-router-dom';
import {
  FlagIcon,
  PlusIcon,
  PencilIcon,
  TrashIcon,
  ChartBarIcon,
  CalendarIcon,
  BanknotesIcon,
  CheckCircleIcon,
  ExclamationTriangleIcon,
  ClockIcon,
  ArrowTrendingUpIcon,
  CalculatorIcon,
  XMarkIcon,
} from '@heroicons/react/24/solid';
import type { PortfolioGoal } from '../../../services/portfolio.service';

interface GoalsManagerProps {
  goals: PortfolioGoal[];
  onCreateGoal?: () => void;
  onEditGoal?: (goalId: string) => void;
  onDeleteGoal?: (goalId: string) => void;
  onUpdateProgress?: (goalId: string, amount: number) => void;
  compact?: boolean;
}

// Goal templates
const GOAL_TEMPLATES = [
  { name: 'Fondo de Emergencia', icon: '🛡️', defaultAmount: 5000, description: '3-6 meses de gastos' },
  { name: 'Vacaciones', icon: '✈️', defaultAmount: 3000, description: 'Viaje de ensueño' },
  { name: 'Auto', icon: '🚗', defaultAmount: 20000, description: 'Vehiculo nuevo o usado' },
  { name: 'Casa', icon: '🏠', defaultAmount: 50000, description: 'Enganche de vivienda' },
  { name: 'Retiro', icon: '🌴', defaultAmount: 100000, description: 'Fondo de retiro' },
  { name: 'Educacion', icon: '🎓', defaultAmount: 15000, description: 'Estudios o capacitacion' },
];

interface StatusConfig {
  icon: React.ElementType;
  color: string;
  bgColor: string;
  label: 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',
  },
  at_risk: {
    icon: ClockIcon,
    color: 'text-yellow-500',
    bgColor: 'bg-yellow-100 dark:bg-yellow-900/30',
    label: 'En Riesgo',
  },
  behind: {
    icon: ExclamationTriangleIcon,
    color: 'text-red-500',
    bgColor: 'bg-red-100 dark:bg-red-900/30',
    label: 'Atrasado',
  },
};

// Savings Rate Calculator Modal
interface SavingsCalculatorModalProps {
  isOpen: boolean;
  onClose: () => void;
  goal?: PortfolioGoal;
}

const SavingsCalculatorModal: React.FC<SavingsCalculatorModalProps> = ({
  isOpen,
  onClose,
  goal,
}) => {
  const [targetAmount, setTargetAmount] = useState(goal?.targetAmount?.toString() || '10000');
  const [currentAmount, setCurrentAmount] = useState(goal?.currentAmount?.toString() || '0');
  const [targetMonths, setTargetMonths] = useState('12');
  const [expectedReturn, setExpectedReturn] = useState('8');

  const calculation = useMemo(() => {
    const target = parseFloat(targetAmount) || 0;
    const current = parseFloat(currentAmount) || 0;
    const months = parseInt(targetMonths) || 12;
    const returnRate = (parseFloat(expectedReturn) || 0) / 100 / 12;

    const remaining = target - current;

    // Simple calculation without compound interest
    const simpleMonthly = remaining / months;

    // With compound interest (future value of annuity formula)
    let compoundMonthly = simpleMonthly;
    if (returnRate > 0) {
      const fvFactor = (Math.pow(1 + returnRate, months) - 1) / returnRate;
      compoundMonthly = remaining / fvFactor;
    }

    // Project final value with different savings rates
    const scenarios = [0.5, 0.75, 1, 1.25, 1.5].map((multiplier) => {
      const monthly = simpleMonthly * multiplier;
      let projected = current;
      for (let i = 0; i < months; i++) {
        projected = projected * (1 + returnRate) + monthly;
      }
      return {
        multiplier,
        monthly: monthly,
        projected,
        reachesGoal: projected >= target,
      };
    });

    return {
      remaining,
      simpleMonthly,
      compoundMonthly,
      scenarios,
    };
  }, [targetAmount, currentAmount, targetMonths, expectedReturn]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      <div className="fixed inset-0 bg-black/50 backdrop-blur-sm" onClick={onClose} />
      <div className="relative min-h-screen flex items-center justify-center p-4">
        <div className="relative bg-white dark:bg-gray-800 rounded-2xl shadow-xl w-full max-w-lg">
          {/* Header */}
          <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
            <div className="flex items-center gap-3">
              <div className="p-2 bg-blue-100 dark:bg-blue-900/30 rounded-lg">
                <CalculatorIcon className="w-6 h-6 text-blue-600" />
              </div>
              <h2 className="text-xl font-bold text-gray-900 dark:text-white">
                Calculadora de Ahorro
              </h2>
            </div>
            <button
              onClick={onClose}
              className="p-2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200"
            >
              <XMarkIcon className="w-6 h-6" />
            </button>
          </div>

          {/* Content */}
          <div className="p-6 space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Monto Objetivo ($)
                </label>
                <input
                  type="number"
                  value={targetAmount}
                  onChange={(e) => setTargetAmount(e.target.value)}
                  className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Ahorro Actual ($)
                </label>
                <input
                  type="number"
                  value={currentAmount}
                  onChange={(e) => setCurrentAmount(e.target.value)}
                  className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Plazo (meses)
                </label>
                <input
                  type="number"
                  value={targetMonths}
                  onChange={(e) => setTargetMonths(e.target.value)}
                  className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white"
                />
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                  Rendimiento Anual (%)
                </label>
                <input
                  type="number"
                  value={expectedReturn}
                  onChange={(e) => setExpectedReturn(e.target.value)}
                  className="w-full px-3 py-2 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white"
                />
              </div>
            </div>

            {/* Results */}
            <div className="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
              <h4 className="font-medium text-blue-800 dark:text-blue-200 mb-3">
                Ahorro Mensual Requerido
              </h4>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-xs text-blue-600 dark:text-blue-400">Sin rendimiento</p>
                  <p className="text-xl font-bold text-blue-700 dark:text-blue-300">
                    ${calculation.simpleMonthly.toLocaleString(undefined, { maximumFractionDigits: 0 })}
                  </p>
                </div>
                <div>
                  <p className="text-xs text-blue-600 dark:text-blue-400">Con {expectedReturn}% anual</p>
                  <p className="text-xl font-bold text-blue-700 dark:text-blue-300">
                    ${calculation.compoundMonthly.toLocaleString(undefined, { maximumFractionDigits: 0 })}
                  </p>
                </div>
              </div>
            </div>

            {/* Scenarios */}
            <div className="mt-4">
              <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">
                Escenarios de Ahorro
              </h4>
              <div className="space-y-2">
                {calculation.scenarios.map((scenario) => (
                  <div
                    key={scenario.multiplier}
                    className={`flex items-center justify-between p-2 rounded-lg ${
                      scenario.reachesGoal
                        ? 'bg-green-50 dark:bg-green-900/20'
                        : 'bg-gray-50 dark:bg-gray-700/50'
                    }`}
                  >
                    <div className="flex items-center gap-2">
                      {scenario.reachesGoal ? (
                        <CheckCircleIcon className="w-4 h-4 text-green-500" />
                      ) : (
                        <ExclamationTriangleIcon className="w-4 h-4 text-gray-400" />
                      )}
                      <span className="text-sm text-gray-700 dark:text-gray-300">
                        ${scenario.monthly.toLocaleString(undefined, { maximumFractionDigits: 0 })}/mes
                      </span>
                    </div>
                    <span className={`text-sm font-medium ${
                      scenario.reachesGoal ? 'text-green-600' : 'text-gray-500'
                    }`}>
                      ${scenario.projected.toLocaleString(undefined, { maximumFractionDigits: 0 })}
                    </span>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// Progress Update Modal
interface ProgressModalProps {
  isOpen: boolean;
  onClose: () => void;
  goal: PortfolioGoal;
  onSave: (amount: number) => void;
}

const ProgressModal: React.FC<ProgressModalProps> = ({
  isOpen,
  onClose,
  goal,
  onSave,
}) => {
  const [amount, setAmount] = useState(goal.currentAmount.toString());

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      <div className="fixed inset-0 bg-black/50 backdrop-blur-sm" onClick={onClose} />
      <div className="relative min-h-screen flex items-center justify-center p-4">
        <div className="relative bg-white dark:bg-gray-800 rounded-2xl shadow-xl w-full max-w-md">
          <div className="p-6">
            <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-4">
              Actualizar Progreso: {goal.name}
            </h3>
            <div className="mb-4">
              <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
                Monto Actual ($)
              </label>
              <input
                type="number"
                value={amount}
                onChange={(e) => setAmount(e.target.value)}
                className="w-full px-4 py-3 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg text-gray-900 dark:text-white"
              />
            </div>
            <div className="flex gap-3">
              <button
                onClick={onClose}
                className="flex-1 py-2 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 font-medium rounded-lg"
              >
                Cancelar
              </button>
              <button
                onClick={() => {
                  onSave(parseFloat(amount));
                  onClose();
                }}
                className="flex-1 py-2 bg-blue-600 text-white font-medium rounded-lg"
              >
                Guardar
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// Goal Timeline Component
interface GoalTimelineProps {
  goals: PortfolioGoal[];
}

const GoalTimeline: React.FC<GoalTimelineProps> = ({ goals }) => {
  // Sort goals by target date
  const sortedGoals = [...goals].sort(
    (a, b) => new Date(a.targetDate).getTime() - new Date(b.targetDate).getTime()
  );

  const now = Date.now();
  const maxDate = Math.max(...sortedGoals.map((g) => new Date(g.targetDate).getTime()));
  const minDate = now;
  const range = maxDate - minDate;

  return (
    <div className="relative">
      <div className="h-2 bg-gray-200 dark:bg-gray-700 rounded-full"></div>
      {sortedGoals.map((goal, index) => {
        const position = ((new Date(goal.targetDate).getTime() - minDate) / range) * 100;
        const statusConfig = STATUS_CONFIGS[goal.status];

        return (
          <div
            key={goal.id}
            className="absolute top-1/2 transform -translate-y-1/2"
            style={{ left: `${Math.min(95, Math.max(5, position))}%` }}
          >
            <div
              className={`w-4 h-4 rounded-full border-2 border-white ${statusConfig.bgColor} cursor-pointer`}
              title={`${goal.name}: ${goal.progress.toFixed(0)}%`}
            />
          </div>
        );
      })}
    </div>
  );
};

export const GoalsManager: React.FC<GoalsManagerProps> = ({
  goals,
  onCreateGoal,
  onEditGoal,
  onDeleteGoal,
  onUpdateProgress,
  compact = false,
}) => {
  const [showCalculator, setShowCalculator] = useState(false);
  const [selectedGoal, setSelectedGoal] = useState<PortfolioGoal | null>(null);
  const [showProgressModal, setShowProgressModal] = useState(false);
  const [progressGoal, setProgressGoal] = useState<PortfolioGoal | null>(null);

  // Summary stats
  const stats = useMemo(() => {
    const total = goals.length;
    const onTrack = goals.filter((g) => g.status === 'on_track').length;
    const atRisk = goals.filter((g) => g.status === 'at_risk').length;
    const behind = goals.filter((g) => g.status === 'behind').length;
    const totalTarget = goals.reduce((sum, g) => sum + g.targetAmount, 0);
    const totalCurrent = goals.reduce((sum, g) => sum + g.currentAmount, 0);
    const avgProgress = total > 0 ? (totalCurrent / totalTarget) * 100 : 0;

    return { total, onTrack, atRisk, behind, totalTarget, totalCurrent, avgProgress };
  }, [goals]);

  const handleProgressUpdate = (goalId: string, amount: number) => {
    if (onUpdateProgress) {
      onUpdateProgress(goalId, amount);
    }
  };

  if (compact) {
    return (
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className="p-2 bg-green-100 dark:bg-green-900/30 rounded-lg">
              <FlagIcon className="w-5 h-5 text-green-600" />
            </div>
            <h3 className="font-bold text-gray-900 dark:text-white">Metas</h3>
          </div>
          {onCreateGoal && (
            <button
              onClick={onCreateGoal}
              className="p-1.5 bg-green-100 dark:bg-green-900/30 rounded-lg text-green-600 hover:bg-green-200 dark:hover:bg-green-900/50"
            >
              <PlusIcon className="w-4 h-4" />
            </button>
          )}
        </div>

        {goals.length > 0 ? (
          <>
            <div className="space-y-3">
              {goals.slice(0, 3).map((goal) => {
                const statusConfig = STATUS_CONFIGS[goal.status];
                return (
                  <div key={goal.id} className="flex items-center gap-3">
                    <div className={`p-1 rounded-full ${statusConfig.bgColor}`}>
                      <statusConfig.icon className={`w-3 h-3 ${statusConfig.color}`} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
                        {goal.name}
                      </p>
                      <div className="h-1.5 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
                        <div
                          className={`h-full rounded-full ${
                            goal.status === 'on_track' ? 'bg-green-500' :
                            goal.status === 'at_risk' ? 'bg-yellow-500' : 'bg-red-500'
                          }`}
                          style={{ width: `${Math.min(100, goal.progress)}%` }}
                        />
                      </div>
                    </div>
                    <span className="text-xs font-medium text-gray-500 dark:text-gray-400">
                      {goal.progress.toFixed(0)}%
                    </span>
                  </div>
                );
              })}
            </div>
            {goals.length > 3 && (
              <p className="text-xs text-gray-500 dark:text-gray-400 mt-3 text-center">
                +{goals.length - 3} metas mas
              </p>
            )}
          </>
        ) : (
          <div className="text-center py-4">
            <p className="text-sm text-gray-500 dark:text-gray-400">
              No hay metas definidas
            </p>
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg">
      {/* Header */}
      <div className="flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-green-100 dark:bg-green-900/30 rounded-lg">
            <FlagIcon className="w-6 h-6 text-green-600" />
          </div>
          <div>
            <h3 className="font-bold text-gray-900 dark:text-white">Gestor de Metas</h3>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {stats.total} meta(s) | {stats.avgProgress.toFixed(0)}% progreso promedio
            </p>
          </div>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => {
              setSelectedGoal(null);
              setShowCalculator(true);
            }}
            className="p-2 bg-gray-100 dark:bg-gray-700 rounded-lg text-gray-600 dark:text-gray-400 hover:bg-gray-200 dark:hover:bg-gray-600"
            title="Calculadora de Ahorro"
          >
            <CalculatorIcon className="w-5 h-5" />
          </button>
          {onCreateGoal && (
            <button
              onClick={onCreateGoal}
              className="px-4 py-2 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg flex items-center gap-2"
            >
              <PlusIcon className="w-5 h-5" />
              Nueva Meta
            </button>
          )}
        </div>
      </div>

      {/* Content */}
      <div className="p-6">
        {goals.length > 0 ? (
          <>
            {/* Summary Stats */}
            <div className="grid grid-cols-4 gap-4 mb-6">
              <div className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg text-center">
                <p className="text-xs text-gray-500 dark:text-gray-400">Total Metas</p>
                <p className="text-xl font-bold text-gray-900 dark:text-white">{stats.total}</p>
              </div>
              <div className="p-3 bg-green-50 dark:bg-green-900/20 rounded-lg text-center">
                <p className="text-xs text-green-600">En Camino</p>
                <p className="text-xl font-bold text-green-600">{stats.onTrack}</p>
              </div>
              <div className="p-3 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg text-center">
                <p className="text-xs text-yellow-600">En Riesgo</p>
                <p className="text-xl font-bold text-yellow-600">{stats.atRisk}</p>
              </div>
              <div className="p-3 bg-red-50 dark:bg-red-900/20 rounded-lg text-center">
                <p className="text-xs text-red-600">Atrasados</p>
                <p className="text-xl font-bold text-red-600">{stats.behind}</p>
              </div>
            </div>

            {/* Timeline */}
            <div className="mb-6">
              <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
                Linea de Tiempo
              </h4>
              <GoalTimeline goals={goals} />
              <div className="flex justify-between text-xs text-gray-500 dark:text-gray-400 mt-2">
                <span>Hoy</span>
                <span>
                  {new Date(Math.max(...goals.map(g => new Date(g.targetDate).getTime()))).toLocaleDateString()}
                </span>
              </div>
            </div>

            {/* Goals List */}
            <div className="space-y-4">
              {goals.map((goal) => {
                const statusConfig = STATUS_CONFIGS[goal.status];
                const StatusIcon = statusConfig.icon;
                const daysRemaining = Math.ceil(
                  (new Date(goal.targetDate).getTime() - Date.now()) / (1000 * 60 * 60 * 24)
                );

                return (
                  <div
                    key={goal.id}
                    className="p-4 bg-gray-50 dark:bg-gray-700/50 rounded-lg"
                  >
                    <div className="flex items-start justify-between mb-3">
                      <div className="flex items-center gap-3">
                        <div className={`p-2 rounded-lg ${statusConfig.bgColor}`}>
                          <StatusIcon className={`w-5 h-5 ${statusConfig.color}`} />
                        </div>
                        <div>
                          <h4 className="font-bold text-gray-900 dark:text-white">
                            {goal.name}
                          </h4>
                          <span className={`text-xs ${statusConfig.color}`}>
                            {statusConfig.label}
                          </span>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => {
                            setSelectedGoal(goal);
                            setShowCalculator(true);
                          }}
                          className="p-1.5 text-gray-400 hover:text-blue-600 transition-colors"
                          title="Calculadora"
                        >
                          <CalculatorIcon className="w-4 h-4" />
                        </button>
                        {onEditGoal && (
                          <button
                            onClick={() => onEditGoal(goal.id)}
                            className="p-1.5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-colors"
                            title="Editar"
                          >
                            <PencilIcon className="w-4 h-4" />
                          </button>
                        )}
                        {onDeleteGoal && (
                          <button
                            onClick={() => {
                              if (confirm('¿Eliminar esta meta?')) {
                                onDeleteGoal(goal.id);
                              }
                            }}
                            className="p-1.5 text-gray-400 hover:text-red-500 transition-colors"
                            title="Eliminar"
                          >
                            <TrashIcon className="w-4 h-4" />
                          </button>
                        )}
                      </div>
                    </div>

                    {/* Progress Bar */}
                    <div className="mb-3">
                      <div className="flex justify-between text-sm mb-1">
                        <span className="text-gray-500 dark:text-gray-400">
                          ${goal.currentAmount.toLocaleString()} de ${goal.targetAmount.toLocaleString()}
                        </span>
                        <span className="font-medium text-gray-900 dark:text-white">
                          {goal.progress.toFixed(1)}%
                        </span>
                      </div>
                      <div className="h-2 bg-gray-200 dark:bg-gray-600 rounded-full overflow-hidden">
                        <div
                          className={`h-full rounded-full transition-all ${
                            goal.status === 'on_track' ? 'bg-green-500' :
                            goal.status === 'at_risk' ? 'bg-yellow-500' : 'bg-red-500'
                          }`}
                          style={{ width: `${Math.min(100, goal.progress)}%` }}
                        />
                      </div>
                    </div>

                    {/* Details */}
                    <div className="grid grid-cols-3 gap-4 text-sm">
                      <div>
                        <p className="text-gray-500 dark:text-gray-400">Fecha Objetivo</p>
                        <p className="font-medium text-gray-900 dark:text-white">
                          {new Date(goal.targetDate).toLocaleDateString()}
                        </p>
                      </div>
                      <div>
                        <p className="text-gray-500 dark:text-gray-400">Dias Restantes</p>
                        <p className={`font-medium ${daysRemaining < 30 ? 'text-red-500' : 'text-gray-900 dark:text-white'}`}>
                          {daysRemaining > 0 ? daysRemaining : 'Vencido'}
                        </p>
                      </div>
                      <div>
                        <p className="text-gray-500 dark:text-gray-400">Aporte Mensual</p>
                        <p className="font-medium text-gray-900 dark:text-white">
                          ${goal.monthlyContribution.toLocaleString()}
                        </p>
                      </div>
                    </div>

                    {/* Update Progress Button */}
                    {onUpdateProgress && (
                      <button
                        onClick={() => {
                          setProgressGoal(goal);
                          setShowProgressModal(true);
                        }}
                        className="mt-3 w-full py-2 bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 text-sm font-medium rounded-lg hover:bg-blue-100 dark:hover:bg-blue-900/50 transition-colors"
                      >
                        Actualizar Progreso
                      </button>
                    )}
                  </div>
                );
              })}
            </div>
          </>
        ) : (
          <div className="text-center py-12">
            <FlagIcon className="w-12 h-12 text-gray-400 mx-auto mb-3" />
            <h4 className="font-medium text-gray-900 dark:text-white mb-1">
              No hay metas definidas
            </h4>
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-4">
              Establece tus objetivos financieros y monitorea tu progreso
            </p>
            {onCreateGoal && (
              <button
                onClick={onCreateGoal}
                className="px-6 py-2 bg-green-600 hover:bg-green-700 text-white font-medium rounded-lg"
              >
                Crear Primera Meta
              </button>
            )}
          </div>
        )}

        {/* Goal Templates */}
        {goals.length === 0 && (
          <div className="mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
            <h4 className="text-sm font-semibold text-gray-700 dark:text-gray-300 mb-3">
              Plantillas de Metas
            </h4>
            <div className="grid grid-cols-3 gap-3">
              {GOAL_TEMPLATES.map((template) => (
                <button
                  key={template.name}
                  className="p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors text-left"
                >
                  <span className="text-2xl">{template.icon}</span>
                  <p className="text-sm font-medium text-gray-900 dark:text-white mt-1">
                    {template.name}
                  </p>
                  <p className="text-xs text-gray-500 dark:text-gray-400">
                    ~${template.defaultAmount.toLocaleString()}
                  </p>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Savings Calculator Modal */}
      <SavingsCalculatorModal
        isOpen={showCalculator}
        onClose={() => setShowCalculator(false)}
        goal={selectedGoal || undefined}
      />

      {/* Progress Update Modal */}
      {progressGoal && (
        <ProgressModal
          isOpen={showProgressModal}
          onClose={() => {
            setShowProgressModal(false);
            setProgressGoal(null);
          }}
          goal={progressGoal}
          onSave={(amount) => handleProgressUpdate(progressGoal.id, amount)}
        />
      )}
    </div>
  );
};

export default GoalsManager;
