/**
 * Create Portfolio Page
 * Form to create a new portfolio with risk profile selection
 */

import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  ShieldCheckIcon,
  ScaleIcon,
  RocketLaunchIcon,
  ArrowLeftIcon,
} from '@heroicons/react/24/solid';
import { createPortfolio, type RiskProfile } from '../../../services/portfolio.service';

// ============================================================================
// Risk Profile Options
// ============================================================================

const RISK_PROFILES: {
  id: RiskProfile;
  name: string;
  description: string;
  icon: React.ElementType;
  color: string;
  bgColor: string;
  features: string[];
}[] = [
  {
    id: 'conservative',
    name: 'Conservador',
    description: 'Prioriza la preservación del capital con menor volatilidad',
    icon: ShieldCheckIcon,
    color: 'text-green-600',
    bgColor: 'bg-green-100 dark:bg-green-900/30',
    features: ['50% Stablecoins', '30% Bitcoin', '20% Ethereum', 'Bajo riesgo'],
  },
  {
    id: 'moderate',
    name: 'Moderado',
    description: 'Balance entre crecimiento y estabilidad',
    icon: ScaleIcon,
    color: 'text-blue-600',
    bgColor: 'bg-blue-100 dark:bg-blue-900/30',
    features: ['20% Stablecoins', '40% Bitcoin', '25% Ethereum', '15% Altcoins'],
  },
  {
    id: 'aggressive',
    name: 'Agresivo',
    description: 'Maximiza el potencial de crecimiento con mayor volatilidad',
    icon: RocketLaunchIcon,
    color: 'text-purple-600',
    bgColor: 'bg-purple-100 dark:bg-purple-900/30',
    features: ['10% Stablecoins', '30% Bitcoin', '25% Ethereum', '35% Altcoins'],
  },
];

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

export default function CreatePortfolio() {
  const navigate = useNavigate();
  const [name, setName] = useState('');
  const [selectedProfile, setSelectedProfile] = useState<RiskProfile | null>(null);
  const [initialValue, setInitialValue] = useState<string>('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

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

    if (!selectedProfile) {
      setError('Selecciona un perfil de riesgo');
      return;
    }

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

      await createPortfolio({
        name: name.trim(),
        riskProfile: selectedProfile,
        initialValue: initialValue ? parseFloat(initialValue) : undefined,
      });

      navigate('/portfolio');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error al crear el portfolio');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="max-w-3xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="mb-8">
        <button
          onClick={() => navigate('/portfolio')}
          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">
          Crear Nuevo Portfolio
        </h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          Configura tu portfolio según tu perfil de riesgo
        </p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-8">
        {/* Portfolio 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 del Portfolio
          </label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Ej: Mi Portfolio Principal"
            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>

        {/* Risk Profile Selection */}
        <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6">
          <label className="block mb-4 font-medium text-gray-900 dark:text-white">
            Perfil de Riesgo
          </label>
          <div className="grid md:grid-cols-3 gap-4">
            {RISK_PROFILES.map((profile) => {
              const Icon = profile.icon;
              const isSelected = selectedProfile === profile.id;

              return (
                <button
                  key={profile.id}
                  type="button"
                  onClick={() => setSelectedProfile(profile.id)}
                  className={`p-4 rounded-xl text-left transition-all ${
                    isSelected
                      ? 'ring-2 ring-blue-500 bg-blue-50 dark:bg-blue-900/20'
                      : 'bg-gray-50 dark:bg-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600'
                  }`}
                >
                  <div className={`p-2 rounded-lg ${profile.bgColor} w-fit mb-3`}>
                    <Icon className={`w-6 h-6 ${profile.color}`} />
                  </div>
                  <h3 className="font-bold text-gray-900 dark:text-white mb-1">
                    {profile.name}
                  </h3>
                  <p className="text-sm text-gray-500 dark:text-gray-400 mb-3">
                    {profile.description}
                  </p>
                  <div className="space-y-1">
                    {profile.features.map((feature, idx) => (
                      <div
                        key={idx}
                        className="text-xs text-gray-600 dark:text-gray-300 flex items-center gap-1"
                      >
                        <span className="w-1.5 h-1.5 rounded-full bg-gray-400" />
                        {feature}
                      </div>
                    ))}
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        {/* Initial Value (Optional) */}
        <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">
            Valor Inicial (Opcional)
          </label>
          <p className="text-sm text-gray-500 dark:text-gray-400 mb-3">
            Indica el valor inicial para simular la distribución
          </p>
          <div className="relative">
            <span className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500">
              $
            </span>
            <input
              type="number"
              value={initialValue}
              onChange={(e) => setInitialValue(e.target.value)}
              placeholder="0.00"
              min="0"
              step="0.01"
              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>

        {/* 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')}
            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 || !selectedProfile}
            className="px-6 py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-blue-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 Portfolio'
            )}
          </button>
        </div>
      </form>
    </div>
  );
}
