/**
 * Investment Dashboard Page
 * Main entry point for investment module showing account summary and performance
 * Epic: OQI-004 Cuentas de Inversion
 */

import React, { useEffect, useState, useRef } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import {
  TrendingUp,
  Shield,
  Zap,
  Wallet,
  ArrowUpRight,
  ArrowDownRight,
  Plus,
  ArrowRight,
  RefreshCw,
} from 'lucide-react';
import { useInvestmentStore } from '../../../stores/investmentStore';

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

type TimeframeKey = '1W' | '1M' | '3M' | '6M' | '1Y' | 'ALL';

interface PerformancePoint {
  date: string;
  value: number;
}

// ============================================================================
// Performance Chart Component
// ============================================================================

interface PortfolioPerformanceChartProps {
  data: PerformancePoint[];
  height?: number;
}

const PortfolioPerformanceChart: React.FC<PortfolioPerformanceChartProps> = ({ data, height = 200 }) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

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

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

    const dpr = window.devicePixelRatio || 1;
    const rect = canvas.getBoundingClientRect();
    canvas.width = rect.width * dpr;
    canvas.height = rect.height * dpr;
    ctx.scale(dpr, dpr);

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

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

    const values = data.map((d) => d.value);
    const minVal = Math.min(...values);
    const maxVal = Math.max(...values);
    const range = maxVal - minVal || 1;
    const paddedMin = minVal - range * 0.1;
    const paddedMax = maxVal + range * 0.1;
    const paddedRange = paddedMax - paddedMin;

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

      const val = paddedMax - (paddedRange / 4) * i;
      ctx.fillStyle = '#9CA3AF';
      ctx.font = '11px system-ui';
      ctx.textAlign = 'right';
      ctx.fillText(`$${val.toLocaleString(undefined, { maximumFractionDigits: 0 })}`, padding.left - 8, y + 4);
    }

    // Map points
    const points = data.map((d, i) => ({
      x: padding.left + (i / (data.length - 1)) * chartWidth,
      y: padding.top + ((paddedMax - d.value) / paddedRange) * innerHeight,
    }));

    // Determine color based on performance
    const isPositive = data[data.length - 1].value >= data[0].value;
    const lineColor = isPositive ? '#10B981' : '#EF4444';
    const fillColor = isPositive ? 'rgba(16, 185, 129, 0.15)' : 'rgba(239, 68, 68, 0.15)';

    // Draw fill
    ctx.beginPath();
    ctx.moveTo(points[0].x, chartHeight - padding.bottom);
    points.forEach((p) => ctx.lineTo(p.x, p.y));
    ctx.lineTo(points[points.length - 1].x, chartHeight - padding.bottom);
    ctx.closePath();
    ctx.fillStyle = fillColor;
    ctx.fill();

    // Draw line
    ctx.beginPath();
    ctx.moveTo(points[0].x, points[0].y);
    for (let i = 1; i < points.length; i++) {
      const prev = points[i - 1];
      const curr = points[i];
      const midX = (prev.x + curr.x) / 2;
      ctx.quadraticCurveTo(prev.x, prev.y, midX, (prev.y + curr.y) / 2);
    }
    ctx.lineTo(points[points.length - 1].x, points[points.length - 1].y);
    ctx.strokeStyle = lineColor;
    ctx.lineWidth = 2;
    ctx.stroke();

    // Draw end dot
    const lastPt = points[points.length - 1];
    ctx.beginPath();
    ctx.arc(lastPt.x, lastPt.y, 4, 0, Math.PI * 2);
    ctx.fillStyle = lineColor;
    ctx.fill();

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

  if (data.length < 2) {
    return (
      <div className="flex items-center justify-center h-48 text-gray-500">
        No hay datos de rendimiento disponibles
      </div>
    );
  }

  return <canvas ref={canvasRef} className="w-full" style={{ height }} />;
};

// ============================================================================
// Quick Action Button Component
// ============================================================================

interface QuickActionProps {
  icon: React.ReactNode;
  label: string;
  description: string;
  to: string;
  color: string;
}

const QuickActionButton: React.FC<QuickActionProps> = ({ icon, label, description, to, color }) => (
  <Link
    to={to}
    className={`flex items-center gap-4 p-4 rounded-xl border border-slate-700 bg-slate-800/50 hover:bg-slate-800 hover:border-slate-600 transition-all group`}
  >
    <div className={`w-12 h-12 rounded-lg ${color} flex items-center justify-center`}>{icon}</div>
    <div className="flex-1">
      <div className="font-medium text-white group-hover:text-blue-400 transition-colors">{label}</div>
      <div className="text-sm text-slate-400">{description}</div>
    </div>
    <ArrowRight className="w-5 h-5 text-slate-500 group-hover:text-blue-400 transition-colors" />
  </Link>
);

// ============================================================================
// Account Card Component
// ============================================================================

interface AccountCardProps {
  account: {
    id: string;
    product: { code: string; name: string; riskProfile: string };
    balance: number;
    totalDeposited: number;
    totalEarnings: number;
    unrealizedPnlPercent: number;
    status: string;
  };
}

const AccountCard: React.FC<AccountCardProps> = ({ account }) => {
  const icons: Record<string, React.ReactNode> = {
    atlas: <Shield className="w-5 h-5 text-blue-400" />,
    orion: <TrendingUp className="w-5 h-5 text-purple-400" />,
    nova: <Zap className="w-5 h-5 text-amber-400" />,
  };

  const isPositive = account.totalEarnings >= 0;

  return (
    <Link
      to={`/investment/accounts/${account.id}`}
      className="p-4 rounded-xl border border-slate-700 bg-slate-800/50 hover:bg-slate-800 hover:border-slate-600 transition-all"
    >
      <div className="flex items-center gap-3 mb-3">
        <div className="w-10 h-10 rounded-lg bg-slate-700 flex items-center justify-center">
          {icons[account.product.code] || <Wallet className="w-5 h-5 text-slate-400" />}
        </div>
        <div className="flex-1">
          <div className="font-medium text-white">{account.product.name}</div>
          <div className="text-xs text-slate-500 capitalize">{account.product.riskProfile}</div>
        </div>
        <div className={`flex items-center gap-1 text-sm ${isPositive ? 'text-emerald-400' : 'text-red-400'}`}>
          {isPositive ? <ArrowUpRight className="w-4 h-4" /> : <ArrowDownRight className="w-4 h-4" />}
          {account.unrealizedPnlPercent.toFixed(2)}%
        </div>
      </div>
      <div className="flex items-end justify-between">
        <div>
          <div className="text-xs text-slate-500">Balance</div>
          <div className="text-xl font-bold text-white">
            ${account.balance.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </div>
        </div>
        <div className="text-right">
          <div className="text-xs text-slate-500">Ganancias</div>
          <div className={`font-medium ${isPositive ? 'text-emerald-400' : 'text-red-400'}`}>
            {isPositive ? '+' : ''}${Math.abs(account.totalEarnings).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
          </div>
        </div>
      </div>
    </Link>
  );
};

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

export default function Investment() {
  const navigate = useNavigate();
  const {
    accounts,
    accountSummary,
    loadingAccounts,
    loadingSummary,
    fetchAccounts,
    fetchAccountSummary,
  } = useInvestmentStore();

  const [timeframe, setTimeframe] = useState<TimeframeKey>('1M');
  const [performanceData, setPerformanceData] = useState<PerformancePoint[]>([]);
  const [loadingPerformance, setLoadingPerformance] = useState(false);

  const timeframes: { key: TimeframeKey; label: string }[] = [
    { key: '1W', label: '1S' },
    { key: '1M', label: '1M' },
    { key: '3M', label: '3M' },
    { key: '6M', label: '6M' },
    { key: '1Y', label: '1A' },
    { key: 'ALL', label: 'Todo' },
  ];

  useEffect(() => {
    fetchAccounts();
    fetchAccountSummary();
  }, [fetchAccounts, fetchAccountSummary]);

  useEffect(() => {
    generateMockPerformanceData();
  }, [timeframe, accountSummary]);

  const generateMockPerformanceData = () => {
    if (!accountSummary || accountSummary.totalBalance === 0) {
      setPerformanceData([]);
      return;
    }

    setLoadingPerformance(true);

    const daysMap: Record<TimeframeKey, number> = {
      '1W': 7,
      '1M': 30,
      '3M': 90,
      '6M': 180,
      '1Y': 365,
      ALL: 730,
    };

    const days = daysMap[timeframe];
    const data: PerformancePoint[] = [];
    const baseValue = accountSummary.totalDeposited;
    const currentValue = accountSummary.totalBalance;
    const growthRate = (currentValue - baseValue) / baseValue;

    for (let i = days; i >= 0; i--) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      const progress = (days - i) / days;
      const randomVariation = (Math.random() - 0.5) * 0.02;
      const value = baseValue * (1 + growthRate * progress + randomVariation);

      data.push({
        date: date.toISOString(),
        value: Math.max(0, value),
      });
    }

    data[data.length - 1].value = currentValue;

    setPerformanceData(data);
    setLoadingPerformance(false);
  };

  const handleRefresh = () => {
    fetchAccounts();
    fetchAccountSummary();
  };

  const activeAccounts = accounts.filter((a) => a.status === 'active');
  const hasAccounts = accounts.length > 0;
  const isLoading = loadingAccounts || loadingSummary;

  const totalReturn = accountSummary ? accountSummary.overallReturnPercent : 0;
  const isPositiveReturn = totalReturn >= 0;

  return (
    <div className="max-w-7xl mx-auto px-4 py-8 space-y-8">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold text-white">Dashboard de Inversion</h1>
          <p className="text-slate-400 mt-1">Gestiona tus cuentas de inversion con agentes IA</p>
        </div>
        <div className="flex items-center gap-3">
          <button
            onClick={handleRefresh}
            disabled={isLoading}
            className="p-2 rounded-lg bg-slate-800 border border-slate-700 hover:border-slate-600 transition-colors disabled:opacity-50"
          >
            <RefreshCw className={`w-5 h-5 text-slate-400 ${isLoading ? 'animate-spin' : ''}`} />
          </button>
          <Link
            to="/investment/products"
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
          >
            <Plus className="w-5 h-5" />
            Nueva Inversion
          </Link>
        </div>
      </div>

      {/* Account Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="p-5 rounded-xl bg-gradient-to-br from-blue-600/20 to-blue-800/20 border border-blue-500/30">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center">
              <Wallet className="w-5 h-5 text-blue-400" />
            </div>
            <span className="text-sm text-slate-400">Valor Total</span>
          </div>
          <div className="text-2xl font-bold text-white">
            ${(accountSummary?.totalBalance || 0).toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </div>
        </div>

        <div className="p-5 rounded-xl bg-gradient-to-br from-purple-600/20 to-purple-800/20 border border-purple-500/30">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-10 h-10 rounded-lg bg-purple-500/20 flex items-center justify-center">
              <ArrowUpRight className="w-5 h-5 text-purple-400" />
            </div>
            <span className="text-sm text-slate-400">Total Invertido</span>
          </div>
          <div className="text-2xl font-bold text-white">
            ${(accountSummary?.totalDeposited || 0).toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </div>
        </div>

        <div className={`p-5 rounded-xl border ${isPositiveReturn ? 'bg-gradient-to-br from-emerald-600/20 to-emerald-800/20 border-emerald-500/30' : 'bg-gradient-to-br from-red-600/20 to-red-800/20 border-red-500/30'}`}>
          <div className="flex items-center gap-3 mb-3">
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${isPositiveReturn ? 'bg-emerald-500/20' : 'bg-red-500/20'}`}>
              <TrendingUp className={`w-5 h-5 ${isPositiveReturn ? 'text-emerald-400' : 'text-red-400'}`} />
            </div>
            <span className="text-sm text-slate-400">Rendimiento Total</span>
          </div>
          <div className={`text-2xl font-bold ${isPositiveReturn ? 'text-emerald-400' : 'text-red-400'}`}>
            {isPositiveReturn ? '+' : ''}{totalReturn.toFixed(2)}%
          </div>
          <div className={`text-sm ${isPositiveReturn ? 'text-emerald-400/70' : 'text-red-400/70'}`}>
            {isPositiveReturn ? '+' : ''}${Math.abs(accountSummary?.overallReturn || 0).toLocaleString(undefined, { minimumFractionDigits: 2 })}
          </div>
        </div>

        <div className="p-5 rounded-xl bg-gradient-to-br from-amber-600/20 to-amber-800/20 border border-amber-500/30">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-10 h-10 rounded-lg bg-amber-500/20 flex items-center justify-center">
              <Shield className="w-5 h-5 text-amber-400" />
            </div>
            <span className="text-sm text-slate-400">Cuentas Activas</span>
          </div>
          <div className="text-2xl font-bold text-white">{activeAccounts.length}</div>
          <div className="text-sm text-slate-500">de {accounts.length} total</div>
        </div>
      </div>

      {/* Performance Chart */}
      <div className="rounded-xl bg-slate-800/50 border border-slate-700 p-6">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-lg font-semibold text-white">Rendimiento del Portfolio</h2>
          <div className="flex gap-1">
            {timeframes.map((tf) => (
              <button
                key={tf.key}
                onClick={() => setTimeframe(tf.key)}
                className={`px-3 py-1.5 text-sm rounded-lg font-medium transition-colors ${
                  timeframe === tf.key
                    ? 'bg-blue-600 text-white'
                    : 'bg-slate-700 text-slate-300 hover:bg-slate-600'
                }`}
              >
                {tf.label}
              </button>
            ))}
          </div>
        </div>

        {loadingPerformance ? (
          <div className="flex items-center justify-center h-48">
            <RefreshCw className="w-8 h-8 text-slate-500 animate-spin" />
          </div>
        ) : (
          <PortfolioPerformanceChart data={performanceData} height={200} />
        )}
      </div>

      {/* My Accounts Section */}
      <div>
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-lg font-semibold text-white">Mis Cuentas</h2>
          {hasAccounts && (
            <Link to="/investment/portfolio" className="text-sm text-blue-400 hover:text-blue-300">
              Ver todas
            </Link>
          )}
        </div>

        {isLoading ? (
          <div className="flex items-center justify-center py-12">
            <RefreshCw className="w-8 h-8 text-slate-500 animate-spin" />
          </div>
        ) : hasAccounts ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            {activeAccounts.slice(0, 3).map((account) => (
              <AccountCard key={account.id} account={account} />
            ))}
          </div>
        ) : (
          <div className="text-center py-12 rounded-xl bg-slate-800/30 border border-slate-700">
            <Wallet className="w-12 h-12 text-slate-600 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-white mb-2">No tienes cuentas de inversion activas</h3>
            <p className="text-slate-400 mb-6">Comienza a invertir con nuestros agentes de IA</p>
            <Link
              to="/investment/products"
              className="inline-flex items-center gap-2 px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors"
            >
              <Plus className="w-5 h-5" />
              Abrir Nueva Cuenta
            </Link>
          </div>
        )}
      </div>

      {/* Quick Actions */}
      <div>
        <h2 className="text-lg font-semibold text-white mb-4">Acciones Rapidas</h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <QuickActionButton
            icon={<Plus className="w-6 h-6 text-blue-400" />}
            label="Depositar"
            description="Agregar fondos a tus cuentas"
            to="/investment/deposit"
            color="bg-blue-500/20"
          />
          <QuickActionButton
            icon={<ArrowDownRight className="w-6 h-6 text-purple-400" />}
            label="Retirar"
            description="Solicitar retiro de fondos"
            to="/investment/withdraw"
            color="bg-purple-500/20"
          />
          <QuickActionButton
            icon={<TrendingUp className="w-6 h-6 text-emerald-400" />}
            label="Ver Productos"
            description="Explorar opciones de inversion"
            to="/investment/products"
            color="bg-emerald-500/20"
          />
        </div>
      </div>

      {/* Risk Warning */}
      <div className="p-4 rounded-xl bg-yellow-900/20 border border-yellow-800/50">
        <p className="text-sm text-yellow-400">
          <strong>Aviso de Riesgo:</strong> El trading e inversion conlleva riesgos significativos.
          Los rendimientos objetivo no estan garantizados. Puede perder parte o la totalidad de su inversion.
          Solo invierta capital que pueda permitirse perder.
        </p>
      </div>
    </div>
  );
}
