/**
 * Create Goal Page
 * Form to create a new financial goal
 */

import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeftIcon, CalendarIcon, BanknotesIcon } from '@heroicons/react/24/solid';
import { createGoal } from '../../../services/portfolio.service';

// ============================================================================
// Preset Goals
// ============================================================================

const GOAL_PRESETS = [
  { name: 'Fondo de Emergencia', icon: '🛡️', amount: 5000 },
  { name: 'Vacaciones', icon: '✈️', amount: 3000 },
  { name: 'Auto Nuevo', icon: '🚗', amount: 20000 },
  { name: 'Casa Propia', icon: '🏠', amount: 50000 },
  { name: 'Retiro', icon: '🌴', amount: 100000 },
  { name: 'Educación', icon: '🎓', amount: 15000 },
];

// ============================================================================
// Main Component
// ============================================================================

export default function CreateGoal() {
  const navigate = useNavigate();
  const [name, setName] = useState('');
  const [targetAmount, setTargetAmount] = useState('');
  const [targetDate, setTargetDate] = useState('');
  const [monthlyContribution, setMonthlyContribution] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Calculate suggested monthly contribution
  const calculateSuggestion = () => {
    if (!targetAmount || !targetDate) return null;

    const target = parseFloat(targetAmount);
    const months = Math.ceil(
      (new Date(targetDate).getTime() - Date.now()) / (1000 * 60 * 60 * 24 * 30)
    );

    if (months <= 0 || isNaN(target)) return null;

    return (target / months).toFixed(2);
  };

  const suggestedContribution = calculateSuggestion();

  const handlePresetSelect = (preset: typeof GOAL_PRESETS[0]) => {
    setName(preset.name);
    setTargetAmount(preset.amount.toString());
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!name.trim()) {
      setError('El nombre es requerido');
      return;
    }

    if (!targetAmount || parseFloat(targetAmount) <= 0) {
      setError('El monto objetivo debe ser mayor a 0');
      return;
    }

    if (!targetDate) {
      setError('La fecha objetivo es requerida');
      return;
    }

    if (new Date(targetDate) <= new Date()) {
      setError('La fecha objetivo debe ser en el futuro');
      return;
    }

    try {
      setLoading(true);
      setError(null);

      await createGoal({
        name: name.trim(),
        targetAmount: parseFloat(targetAmount),
        targetDate,
        monthlyContribution: monthlyContribution
          ? parseFloat(monthlyContribution)
          : parseFloat(suggestedContribution || '0'),
      });

      navigate('/portfolio?tab=goals');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al crear la meta');
    } finally {
      setLoading(false);
    }
  };

  // Calculate minimum date (tomorrow)
  const minDate = new Date();
  minDate.setDate(minDate.getDate() + 1);
  const minDateStr = minDate.toISOString().split('T')[0];

  return (
    <div className="max-w-2xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="mb-8">
        <button
          onClick={() => navigate('/portfolio?tab=goals')}
          className="flex items-center gap-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white mb-4"
        >
          <ArrowLeftIcon className="w-5 h-5" />
          Volver
        </button>
        <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
          Nueva Meta Financiera
        </h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          Establece un objetivo y monitorea tu progreso
        </p>
      </div>

      {/* Preset Goals */}
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 mb-6">
        <label className="block mb-3 font-medium text-gray-900 dark:text-white">
          Metas Predefinidas
        </label>
        <div className="grid grid-cols-3 md:grid-cols-6 gap-2">
          {GOAL_PRESETS.map((preset) => (
            <button
              key={preset.name}
              type="button"
              onClick={() => handlePresetSelect(preset)}
              className="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-600 transition-colors text-center"
            >
              <span className="text-2xl block mb-1">{preset.icon}</span>
              <span className="text-xs text-gray-600 dark:text-gray-400">
                {preset.name}
              </span>
            </button>
          ))}
        </div>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Goal Name */}
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
          <label className="block mb-2 font-medium text-gray-900 dark:text-white">
            Nombre de la Meta
          </label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Ej: Fondo de emergencia"
            className="w-full px-4 py-3 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900 dark:text-white"
          />
        </div>

        {/* Target Amount & Date */}
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 space-y-4">
          <div>
            <label className="block mb-2 font-medium text-gray-900 dark:text-white">
              <BanknotesIcon className="w-5 h-5 inline mr-2 text-gray-400" />
              Monto Objetivo
            </label>
            <div className="relative">
              <span className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500">
                $
              </span>
              <input
                type="number"
                value={targetAmount}
                onChange={(e) => setTargetAmount(e.target.value)}
                placeholder="10,000"
                min="1"
                step="1"
                className="w-full pl-8 pr-4 py-3 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900 dark:text-white"
              />
            </div>
          </div>

          <div>
            <label className="block mb-2 font-medium text-gray-900 dark:text-white">
              <CalendarIcon className="w-5 h-5 inline mr-2 text-gray-400" />
              Fecha Objetivo
            </label>
            <input
              type="date"
              value={targetDate}
              onChange={(e) => setTargetDate(e.target.value)}
              min={minDateStr}
              className="w-full px-4 py-3 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900 dark:text-white"
            />
          </div>
        </div>

        {/* Monthly Contribution */}
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
          <label className="block mb-2 font-medium text-gray-900 dark:text-white">
            Aporte Mensual
          </label>
          {suggestedContribution && (
            <p className="text-sm text-gray-500 dark:text-gray-400 mb-3">
              Sugerido: ${suggestedContribution}/mes para alcanzar tu meta
            </p>
          )}
          <div className="relative">
            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500">
              $
            </span>
            <input
              type="number"
              value={monthlyContribution}
              onChange={(e) => setMonthlyContribution(e.target.value)}
              placeholder={suggestedContribution || '500'}
              min="0"
              step="1"
              className="w-full pl-8 pr-4 py-3 bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-gray-900 dark:text-white"
            />
          </div>
          {suggestedContribution && !monthlyContribution && (
            <button
              type="button"
              onClick={() => setMonthlyContribution(suggestedContribution)}
              className="mt-2 text-sm text-blue-600 hover:text-blue-700"
            >
              Usar monto sugerido
            </button>
          )}
        </div>

        {/* Summary Preview */}
        {name && targetAmount && targetDate && (
          <div className="bg-green-50 dark:bg-green-900/20 rounded-xl p-6 border border-green-200 dark:border-green-800">
            <h3 className="font-bold text-gray-900 dark:text-white mb-3">
              Resumen de tu Meta
            </h3>
            <div className="space-y-2 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-600 dark:text-gray-400">Meta</span>
                <span className="text-gray-900 dark:text-white font-medium">
                  {name}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600 dark:text-gray-400">Objetivo</span>
                <span className="text-gray-900 dark:text-white font-medium">
                  ${parseFloat(targetAmount).toLocaleString()}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600 dark:text-gray-400">Fecha</span>
                <span className="text-gray-900 dark:text-white font-medium">
                  {new Date(targetDate).toLocaleDateString()}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-600 dark:text-gray-400">
                  Aporte mensual
                </span>
                <span className="text-green-600 font-medium">
                  ${monthlyContribution || suggestedContribution || '0'}/mes
                </span>
              </div>
            </div>
          </div>
        )}

        {/* Error Message */}
        {error && (
          <div className="p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
            <p className="text-red-600 dark:text-red-400">{error}</p>
          </div>
        )}

        {/* Submit Button */}
        <div className="flex justify-end gap-4">
          <button
            type="button"
            onClick={() => navigate('/portfolio?tab=goals')}
            className="px-6 py-3 bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 font-medium rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 transition-colors"
          >
            Cancelar
          </button>
          <button
            type="submit"
            disabled={loading}
            className="px-6 py-3 bg-green-600 hover:bg-green-700 disabled:bg-green-400 text-white font-medium rounded-lg transition-colors flex items-center gap-2"
          >
            {loading ? (
              <>
                <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
                Creando...
              </>
            ) : (
              'Crear Meta'
            )}
          </button>
        </div>
      </form>
    </div>
  );
}
