/**
 * Product Detail Page
 * Shows detailed information about an investment product
 */

import React, { useEffect, useState, useRef } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { ArrowLeft, Shield, TrendingUp, Zap, AlertCircle, Info, CheckCircle } from 'lucide-react';
import investmentService, { Product, ProductPerformance } from '../../../services/investment.service';

// ============================================================================
// Types
// ============================================================================

type Period = 'week' | 'month' | '3months' | 'year';

// ============================================================================
// Subcomponents
// ============================================================================

interface PerformanceChartProps {
  data: ProductPerformance[];
}

const PerformanceChart: React.FC<PerformanceChartProps> = ({ data }) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas || data.length === 0) return;

    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const width = canvas.width;
    const height = canvas.height;
    const padding = { top: 20, right: 20, bottom: 40, left: 60 };
    const chartWidth = width - padding.left - padding.right;
    const chartHeight = height - padding.top - padding.bottom;

    ctx.clearRect(0, 0, width, height);

    const returns = data.map(d => d.cumulativeReturn * 100);
    const minReturn = Math.min(...returns, 0) - 5;
    const maxReturn = Math.max(...returns) + 5;

    // Draw grid
    ctx.strokeStyle = '#374151';
    ctx.lineWidth = 0.5;
    for (let i = 0; i <= 4; i++) {
      const y = padding.top + (chartHeight / 4) * i;
      ctx.beginPath();
      ctx.moveTo(padding.left, y);
      ctx.lineTo(width - padding.right, y);
      ctx.stroke();

      const value = maxReturn - ((maxReturn - minReturn) / 4) * i;
      ctx.fillStyle = '#9CA3AF';
      ctx.font = '11px system-ui';
      ctx.textAlign = 'right';
      ctx.fillText(`${value.toFixed(1)}%`, padding.left - 10, y + 4);
    }

    // Zero line
    const zeroY = padding.top + ((maxReturn - 0) / (maxReturn - minReturn)) * chartHeight;
    ctx.strokeStyle = '#6B7280';
    ctx.lineWidth = 1;
    ctx.setLineDash([5, 5]);
    ctx.beginPath();
    ctx.moveTo(padding.left, zeroY);
    ctx.lineTo(width - padding.right, zeroY);
    ctx.stroke();
    ctx.setLineDash([]);

    // Draw line
    const isPositive = returns[returns.length - 1] >= 0;
    ctx.beginPath();
    ctx.strokeStyle = isPositive ? '#10B981' : '#EF4444';
    ctx.lineWidth = 2;

    data.forEach((point, i) => {
      const x = padding.left + (chartWidth / (data.length - 1)) * i;
      const y = padding.top + ((maxReturn - point.cumulativeReturn * 100) / (maxReturn - minReturn)) * chartHeight;

      if (i === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
    });
    ctx.stroke();

    // Gradient fill
    const gradient = ctx.createLinearGradient(0, padding.top, 0, height - padding.bottom);
    gradient.addColorStop(0, isPositive ? 'rgba(16, 185, 129, 0.2)' : 'rgba(239, 68, 68, 0.2)');
    gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');

    ctx.beginPath();
    data.forEach((point, i) => {
      const x = padding.left + (chartWidth / (data.length - 1)) * i;
      const y = padding.top + ((maxReturn - point.cumulativeReturn * 100) / (maxReturn - minReturn)) * chartHeight;
      if (i === 0) ctx.moveTo(x, y);
      else ctx.lineTo(x, y);
    });
    ctx.lineTo(padding.left + chartWidth, zeroY);
    ctx.lineTo(padding.left, zeroY);
    ctx.closePath();
    ctx.fillStyle = gradient;
    ctx.fill();

    // X-axis labels
    const labelIndices = [0, Math.floor(data.length / 2), data.length - 1];
    ctx.fillStyle = '#9CA3AF';
    ctx.font = '11px system-ui';
    ctx.textAlign = 'center';
    labelIndices.forEach(i => {
      if (data[i]) {
        const x = padding.left + (chartWidth / (data.length - 1)) * i;
        const date = new Date(data[i].date);
        ctx.fillText(date.toLocaleDateString('es-ES', { month: 'short', day: 'numeric' }), x, height - 15);
      }
    });
  }, [data]);

  return <canvas ref={canvasRef} width={800} height={300} className="w-full h-auto" />;
};

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

export const ProductDetail: React.FC = () => {
  const { productId } = useParams<{ productId: string }>();
  const navigate = useNavigate();

  const [product, setProduct] = useState<Product | null>(null);
  const [performance, setPerformance] = useState<ProductPerformance[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [period, setPeriod] = useState<Period>('month');
  const [investing, setInvesting] = useState(false);
  const [investAmount, setInvestAmount] = useState<number>(1000);

  useEffect(() => {
    if (productId) {
      loadProduct();
    }
  }, [productId]);

  useEffect(() => {
    if (productId) {
      loadPerformance();
    }
  }, [productId, period]);

  const loadProduct = async () => {
    if (!productId) return;

    try {
      setLoading(true);
      setError(null);
      const data = await investmentService.getProductById(productId);
      setProduct(data);
      setInvestAmount(data.minInvestment);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error loading product');
    } finally {
      setLoading(false);
    }
  };

  const loadPerformance = async () => {
    if (!productId) return;

    try {
      const data = await investmentService.getProductPerformance(productId, period);
      setPerformance(data);
    } catch (err) {
      console.error('Error loading performance:', err);
    }
  };

  const handleInvest = async () => {
    if (!product || investing) return;

    try {
      setInvesting(true);
      await investmentService.createAccount(product.id, investAmount);
      navigate('/investment/portfolio');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Error creating account');
    } finally {
      setInvesting(false);
    }
  };

  const periodOptions: { value: Period; label: string }[] = [
    { value: 'week', label: '7 días' },
    { value: 'month', label: '30 días' },
    { value: '3months', label: '3 meses' },
    { value: 'year', label: '1 año' },
  ];

  const icons: Record<string, React.ReactNode> = {
    atlas: <Shield className="w-8 h-8 text-blue-500" />,
    orion: <TrendingUp className="w-8 h-8 text-purple-500" />,
    nova: <Zap className="w-8 h-8 text-orange-500" />,
  };

  const riskColors = {
    conservative: 'text-green-500 bg-green-100 dark:bg-green-900/30',
    moderate: 'text-yellow-500 bg-yellow-100 dark:bg-yellow-900/30',
    aggressive: 'text-red-500 bg-red-100 dark:bg-red-900/30',
  };

  const riskLabels = {
    conservative: 'Conservador',
    moderate: 'Moderado',
    aggressive: 'Agresivo',
  };

  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>
    );
  }

  if (error || !product) {
    return (
      <div className="max-w-4xl mx-auto px-4 py-8">
        <div className="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl p-6 text-center">
          <AlertCircle className="w-12 h-12 text-red-500 mx-auto mb-4" />
          <h2 className="text-xl font-bold text-red-700 dark:text-red-400 mb-2">
            Error al cargar el producto
          </h2>
          <p className="text-red-600 dark:text-red-300 mb-4">{error || 'Producto no encontrado'}</p>
          <button
            onClick={() => navigate('/investment/products')}
            className="px-6 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
          >
            Volver a Productos
          </button>
        </div>
      </div>
    );
  }

  const currentReturn = performance.length > 0 ? performance[performance.length - 1].cumulativeReturn * 100 : 0;

  return (
    <div className="max-w-6xl mx-auto px-4 py-8">
      {/* Header */}
      <div className="flex items-center gap-4 mb-8">
        <button
          onClick={() => navigate('/investment/products')}
          className="p-2 rounded-lg bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700"
        >
          <ArrowLeft className="w-5 h-5 text-gray-600 dark:text-gray-400" />
        </button>
        <div className="flex-1">
          <div className="flex items-center gap-3">
            {icons[product.code] || icons.atlas}
            <div>
              <h1 className="text-2xl font-bold text-gray-900 dark:text-white">
                {product.name}
              </h1>
              <span className={`px-3 py-1 rounded-full text-sm font-medium ${riskColors[product.riskProfile]}`}>
                {riskLabels[product.riskProfile]}
              </span>
            </div>
          </div>
        </div>
      </div>

      <div className="grid lg:grid-cols-3 gap-8">
        {/* Main Content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Description */}
          <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
            <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-4">
              Descripción
            </h2>
            <p className="text-gray-600 dark:text-gray-400">
              {product.description}
            </p>
          </div>

          {/* Performance Chart */}
          <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-bold text-gray-900 dark:text-white">
                Rendimiento Histórico
              </h2>
              <div className="flex gap-1">
                {periodOptions.map(option => (
                  <button
                    key={option.value}
                    onClick={() => setPeriod(option.value)}
                    className={`px-3 py-1 rounded-lg text-sm font-medium transition-colors ${
                      period === option.value
                        ? 'bg-blue-600 text-white'
                        : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
                    }`}
                  >
                    {option.label}
                  </button>
                ))}
              </div>
            </div>
            {performance.length > 0 ? (
              <>
                <PerformanceChart data={performance} />
                <div className="mt-4 text-center">
                  <p className="text-sm text-gray-500 dark:text-gray-400">Retorno acumulado</p>
                  <p className={`text-3xl font-bold ${currentReturn >= 0 ? 'text-green-500' : 'text-red-500'}`}>
                    {currentReturn >= 0 ? '+' : ''}{currentReturn.toFixed(2)}%
                  </p>
                </div>
              </>
            ) : (
              <p className="text-gray-500 dark:text-gray-400 text-center py-12">
                No hay datos de rendimiento disponibles
              </p>
            )}
          </div>

          {/* Features */}
          <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg">
            <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-4">
              Características
            </h2>
            <div className="grid md:grid-cols-2 gap-4">
              <div className="flex items-start gap-3">
                <CheckCircle className="w-5 h-5 text-green-500 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="font-medium text-gray-900 dark:text-white">Target Mensual</p>
                  <p className="text-sm text-gray-500 dark:text-gray-400">
                    {product.targetReturnMin}% - {product.targetReturnMax}%
                  </p>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <CheckCircle className="w-5 h-5 text-green-500 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="font-medium text-gray-900 dark:text-white">Max Drawdown</p>
                  <p className="text-sm text-gray-500 dark:text-gray-400">{product.maxDrawdown}%</p>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <CheckCircle className="w-5 h-5 text-green-500 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="font-medium text-gray-900 dark:text-white">Comisión de Gestión</p>
                  <p className="text-sm text-gray-500 dark:text-gray-400">{product.managementFee}% anual</p>
                </div>
              </div>
              <div className="flex items-start gap-3">
                <CheckCircle className="w-5 h-5 text-green-500 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="font-medium text-gray-900 dark:text-white">Comisión de Éxito</p>
                  <p className="text-sm text-gray-500 dark:text-gray-400">{product.performanceFee}% sobre ganancias</p>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Sidebar - Investment Card */}
        <div className="lg:col-span-1">
          <div className="bg-white dark:bg-gray-800 rounded-xl p-6 shadow-lg sticky top-4">
            <h2 className="text-lg font-bold text-gray-900 dark:text-white mb-6">
              Invertir
            </h2>

            <div className="space-y-4 mb-6">
              <div>
                <label className="block text-sm text-gray-500 dark:text-gray-400 mb-2">
                  Monto a invertir
                </label>
                <div className="relative">
                  <span className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500">$</span>
                  <input
                    type="number"
                    min={product.minInvestment}
                    step="100"
                    value={investAmount}
                    onChange={(e) => setInvestAmount(Number(e.target.value))}
                    className="w-full pl-8 pr-4 py-3 bg-gray-100 dark:bg-gray-900 rounded-lg text-lg font-medium text-gray-900 dark:text-white border-0 focus:ring-2 focus:ring-blue-500"
                  />
                </div>
                <p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
                  Mínimo: ${product.minInvestment.toLocaleString()}
                </p>
              </div>

              <div className="flex gap-2">
                {[500, 1000, 5000, 10000].map(amount => (
                  <button
                    key={amount}
                    onClick={() => setInvestAmount(amount)}
                    className={`flex-1 px-2 py-1.5 text-sm rounded-lg transition-colors ${
                      investAmount === amount
                        ? 'bg-blue-600 text-white'
                        : 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300'
                    }`}
                  >
                    ${amount >= 1000 ? `${amount / 1000}k` : amount}
                  </button>
                ))}
              </div>
            </div>

            <button
              onClick={handleInvest}
              disabled={investing || investAmount < product.minInvestment}
              className="w-full py-3 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors"
            >
              {investing ? 'Procesando...' : 'Invertir Ahora'}
            </button>

            <div className="mt-6 p-4 bg-blue-50 dark:bg-blue-900/20 rounded-lg">
              <div className="flex items-start gap-2">
                <Info className="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" />
                <p className="text-sm text-blue-700 dark:text-blue-300">
                  Tu inversión será gestionada automáticamente por nuestros agentes de IA.
                  Podrás retirar fondos en cualquier momento.
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Risk Warning */}
      <div className="mt-8 p-6 bg-yellow-50 dark:bg-yellow-900/20 rounded-lg border border-yellow-200 dark:border-yellow-800">
        <p className="text-sm text-yellow-800 dark:text-yellow-200">
          <strong>Advertencia de riesgo:</strong> El trading de activos financieros conlleva riesgos significativos.
          Los rendimientos pasados no garantizan rendimientos futuros. Los rendimientos objetivo son estimados
          y pueden variar. Solo invierte lo que puedas permitirte perder.
        </p>
      </div>
    </div>
  );
};

export default ProductDetail;
