/**
 * Edit Allocations Page
 * Form to edit portfolio target allocations
 */

import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import {
  ArrowLeftIcon,
  PlusIcon,
  TrashIcon,
  ExclamationTriangleIcon,
} from '@heroicons/react/24/solid';
import {
  getPortfolio,
  updateAllocations,
  type Portfolio,
} from '../../../services/portfolio.service';

// ============================================================================
// Available Assets
// ============================================================================

const AVAILABLE_ASSETS = [
  { symbol: 'BTC', name: 'Bitcoin', icon: 'https://cryptologos.cc/logos/bitcoin-btc-logo.svg' },
  { symbol: 'ETH', name: 'Ethereum', icon: 'https://cryptologos.cc/logos/ethereum-eth-logo.svg' },
  { symbol: 'USDT', name: 'Tether', icon: 'https://cryptologos.cc/logos/tether-usdt-logo.svg' },
  { symbol: 'SOL', name: 'Solana', icon: 'https://cryptologos.cc/logos/solana-sol-logo.svg' },
  { symbol: 'LINK', name: 'Chainlink', icon: 'https://cryptologos.cc/logos/chainlink-link-logo.svg' },
  { symbol: 'AVAX', name: 'Avalanche', icon: 'https://cryptologos.cc/logos/avalanche-avax-logo.svg' },
  { symbol: 'ADA', name: 'Cardano', icon: 'https://cryptologos.cc/logos/cardano-ada-logo.svg' },
  { symbol: 'DOT', name: 'Polkadot', icon: 'https://cryptologos.cc/logos/polkadot-new-dot-logo.svg' },
  { symbol: 'MATIC', name: 'Polygon', icon: 'https://cryptologos.cc/logos/polygon-matic-logo.svg' },
  { symbol: 'UNI', name: 'Uniswap', icon: 'https://cryptologos.cc/logos/uniswap-uni-logo.svg' },
];

interface AllocationInput {
  asset: string;
  targetPercent: number;
}

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

export default function EditAllocations() {
  const navigate = useNavigate();
  const { portfolioId } = useParams<{ portfolioId: string }>();
  const [portfolio, setPortfolio] = useState<Portfolio | null>(null);
  const [allocations, setAllocations] = useState<AllocationInput[]>([]);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showAddModal, setShowAddModal] = useState(false);

  useEffect(() => {
    if (portfolioId) {
      loadPortfolio();
    }
  }, [portfolioId]);

  const loadPortfolio = async () => {
    try {
      setLoading(true);
      const data = await getPortfolio(portfolioId!);
      setPortfolio(data);
      setAllocations(
        data.allocations.map((a) => ({
          asset: a.asset,
          targetPercent: a.targetPercent,
        }))
      );
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error loading portfolio');
    } finally {
      setLoading(false);
    }
  };

  const totalPercent = allocations.reduce((sum, a) => sum + a.targetPercent, 0);
  const isValid = Math.abs(totalPercent - 100) < 0.01;

  const handlePercentChange = (index: number, value: string) => {
    const newAllocations = [...allocations];
    newAllocations[index].targetPercent = parseFloat(value) || 0;
    setAllocations(newAllocations);
  };

  const handleRemove = (index: number) => {
    const newAllocations = allocations.filter((_, i) => i !== index);
    setAllocations(newAllocations);
  };

  const handleAddAsset = (asset: string) => {
    if (allocations.some((a) => a.asset === asset)) {
      setShowAddModal(false);
      return;
    }

    const remaining = Math.max(0, 100 - totalPercent);
    setAllocations([...allocations, { asset, targetPercent: remaining }]);
    setShowAddModal(false);
  };

  const handleAutoBalance = () => {
    if (allocations.length === 0) return;
    const equalPercent = 100 / allocations.length;
    setAllocations(allocations.map((a) => ({ ...a, targetPercent: equalPercent })));
  };

  const handleSubmit = async () => {
    if (!isValid || !portfolioId) {
      setError('Las allocaciones deben sumar 100%');
      return;
    }

    try {
      setSaving(true);
      setError(null);
      await updateAllocations(portfolioId, allocations);
      navigate('/portfolio');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error saving allocations');
    } finally {
      setSaving(false);
    }
  };

  const availableToAdd = AVAILABLE_ASSETS.filter(
    (asset) => !allocations.some((a) => a.asset === asset.symbol)
  );

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-96">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  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">
          Editar Allocaciones
        </h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          {portfolio?.name} - Perfil{' '}
          {portfolio?.riskProfile === 'conservative'
            ? 'Conservador'
            : portfolio?.riskProfile === 'moderate'
            ? 'Moderado'
            : 'Agresivo'}
        </p>
      </div>

      {/* Total indicator */}
      <div
        className={`mb-6 p-4 rounded-xl flex items-center justify-between ${
          isValid
            ? 'bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800'
            : 'bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800'
        }`}
      >
        <div className="flex items-center gap-2">
          {!isValid && <ExclamationTriangleIcon className="w-5 h-5 text-red-500" />}
          <span className="font-medium text-gray-900 dark:text-white">
            Total: {totalPercent.toFixed(1)}%
          </span>
        </div>
        {!isValid && (
          <span className="text-sm text-red-600 dark:text-red-400">
            {totalPercent < 100
              ? `Faltan ${(100 - totalPercent).toFixed(1)}%`
              : `Sobran ${(totalPercent - 100).toFixed(1)}%`}
          </span>
        )}
      </div>

      {/* Allocations list */}
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg p-6 mb-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="font-bold text-gray-900 dark:text-white">Distribución</h2>
          <button
            onClick={handleAutoBalance}
            className="text-sm text-blue-600 hover:text-blue-700"
          >
            Distribuir equitativamente
          </button>
        </div>

        <div className="space-y-4">
          {allocations.map((alloc, index) => {
            const assetInfo = AVAILABLE_ASSETS.find((a) => a.symbol === alloc.asset);
            return (
              <div
                key={alloc.asset}
                className="flex items-center gap-4 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg"
              >
                <div className="flex items-center gap-3 flex-1">
                  {assetInfo?.icon ? (
                    <img src={assetInfo.icon} alt={alloc.asset} className="w-10 h-10" />
                  ) : (
                    <div className="w-10 h-10 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center font-bold text-sm">
                      {alloc.asset.slice(0, 2)}
                    </div>
                  )}
                  <div>
                    <p className="font-medium text-gray-900 dark:text-white">
                      {alloc.asset}
                    </p>
                    <p className="text-sm text-gray-500 dark:text-gray-400">
                      {assetInfo?.name || alloc.asset}
                    </p>
                  </div>
                </div>

                <div className="flex items-center gap-2">
                  <input
                    type="number"
                    value={alloc.targetPercent}
                    onChange={(e) => handlePercentChange(index, e.target.value)}
                    min="0"
                    max="100"
                    step="0.1"
                    className="w-20 px-3 py-2 bg-white dark:bg-gray-600 border border-gray-200 dark:border-gray-500 rounded-lg text-right text-gray-900 dark:text-white"
                  />
                  <span className="text-gray-500 dark:text-gray-400">%</span>
                </div>

                <button
                  onClick={() => handleRemove(index)}
                  className="p-2 text-gray-400 hover:text-red-500 transition-colors"
                >
                  <TrashIcon className="w-5 h-5" />
                </button>

                {/* Visual bar */}
                <div className="w-24 h-2 bg-gray-200 dark:bg-gray-600 rounded-full overflow-hidden">
                  <div
                    className="h-full bg-blue-500 transition-all"
                    style={{ width: `${Math.min(100, alloc.targetPercent)}%` }}
                  />
                </div>
              </div>
            );
          })}
        </div>

        {/* Add asset button */}
        {availableToAdd.length > 0 && (
          <button
            onClick={() => setShowAddModal(true)}
            className="mt-4 w-full py-3 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg text-gray-500 dark:text-gray-400 hover:border-blue-500 hover:text-blue-500 transition-colors flex items-center justify-center gap-2"
          >
            <PlusIcon className="w-5 h-5" />
            Agregar Activo
          </button>
        )}
      </div>

      {/* Error Message */}
      {error && (
        <div className="mb-6 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>
      )}

      {/* Action buttons */}
      <div className="flex justify-end gap-4">
        <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
          onClick={handleSubmit}
          disabled={!isValid || saving}
          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"
        >
          {saving ? (
            <>
              <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
              Guardando...
            </>
          ) : (
            'Guardar Cambios'
          )}
        </button>
      </div>

      {/* Add Asset Modal */}
      {showAddModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-md w-full mx-4 max-h-[80vh] overflow-hidden">
            <div className="p-4 border-b border-gray-200 dark:border-gray-700">
              <h3 className="font-bold text-gray-900 dark:text-white">Agregar Activo</h3>
            </div>
            <div className="p-4 overflow-y-auto max-h-96">
              <div className="space-y-2">
                {availableToAdd.map((asset) => (
                  <button
                    key={asset.symbol}
                    onClick={() => handleAddAsset(asset.symbol)}
                    className="w-full flex items-center gap-3 p-3 bg-gray-50 dark:bg-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-600 transition-colors"
                  >
                    {asset.icon ? (
                      <img src={asset.icon} alt={asset.symbol} className="w-8 h-8" />
                    ) : (
                      <div className="w-8 h-8 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center font-bold text-xs">
                        {asset.symbol.slice(0, 2)}
                      </div>
                    )}
                    <div className="text-left">
                      <p className="font-medium text-gray-900 dark:text-white">
                        {asset.symbol}
                      </p>
                      <p className="text-sm text-gray-500 dark:text-gray-400">
                        {asset.name}
                      </p>
                    </div>
                  </button>
                ))}
              </div>
            </div>
            <div className="p-4 border-t border-gray-200 dark:border-gray-700">
              <button
                onClick={() => setShowAddModal(false)}
                className="w-full py-2 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>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
