/**
 * AccountSummaryCard Component
 * Reusable investment account summary card with key metrics
 * OQI-004: Cuentas de Inversion
 */

import React from 'react';
import {
  Wallet,
  TrendingUp,
  TrendingDown,
  Percent,
  Calendar,
  ArrowUpRight,
  ArrowDownRight,
  MoreVertical,
  Eye,
  Settings,
  Clock,
} from 'lucide-react';

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

export interface InvestmentAccount {
  id: string;
  accountNumber: string;
  productName: string;
  productType: 'atlas' | 'orion' | 'nova' | 'custom';
  currentBalance: number;
  initialDeposit: number;
  totalGains: number;
  totalGainsPercent: number;
  monthlyReturn: number;
  monthlyReturnPercent: number;
  status: 'active' | 'paused' | 'pending' | 'closed';
  riskLevel: 'low' | 'medium' | 'high';
  createdAt: string;
  lastDistributionDate?: string;
  nextDistributionDate?: string;
}

interface AccountSummaryCardProps {
  account: InvestmentAccount;
  onViewDetails?: (accountId: string) => void;
  onManageSettings?: (accountId: string) => void;
  compact?: boolean;
  showActions?: boolean;
}

// ============================================================================
// Helper Functions
// ============================================================================

const getProductColor = (productType: InvestmentAccount['productType']) => {
  switch (productType) {
    case 'atlas':
      return 'from-blue-500 to-blue-600';
    case 'orion':
      return 'from-purple-500 to-purple-600';
    case 'nova':
      return 'from-amber-500 to-amber-600';
    default:
      return 'from-slate-500 to-slate-600';
  }
};

const getStatusBadge = (status: InvestmentAccount['status']) => {
  switch (status) {
    case 'active':
      return { label: 'Active', className: 'bg-emerald-500/20 text-emerald-400' };
    case 'paused':
      return { label: 'Paused', className: 'bg-yellow-500/20 text-yellow-400' };
    case 'pending':
      return { label: 'Pending', className: 'bg-blue-500/20 text-blue-400' };
    case 'closed':
      return { label: 'Closed', className: 'bg-slate-500/20 text-slate-400' };
    default:
      return { label: status, className: 'bg-slate-500/20 text-slate-400' };
  }
};

const getRiskColor = (riskLevel: InvestmentAccount['riskLevel']) => {
  switch (riskLevel) {
    case 'low':
      return 'text-emerald-400';
    case 'medium':
      return 'text-yellow-400';
    case 'high':
      return 'text-red-400';
    default:
      return 'text-slate-400';
  }
};

const formatCurrency = (value: number) => {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(value);
};

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
};

// ============================================================================
// Component
// ============================================================================

export const AccountSummaryCard: React.FC<AccountSummaryCardProps> = ({
  account,
  onViewDetails,
  onManageSettings,
  compact = false,
  showActions = true,
}) => {
  const [showMenu, setShowMenu] = React.useState(false);
  const status = getStatusBadge(account.status);
  const isPositive = account.totalGains >= 0;

  if (compact) {
    return (
      <div
        onClick={() => onViewDetails?.(account.id)}
        className="p-4 bg-slate-800/50 rounded-xl border border-slate-700 hover:border-slate-600 cursor-pointer transition-all"
      >
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-3">
            <div className={`w-10 h-10 rounded-lg bg-gradient-to-br ${getProductColor(account.productType)} flex items-center justify-center`}>
              <Wallet className="w-5 h-5 text-white" />
            </div>
            <div>
              <div className="font-medium text-white">{account.productName}</div>
              <div className="text-xs text-slate-500">{account.accountNumber}</div>
            </div>
          </div>
          <span className={`px-2 py-0.5 rounded text-xs font-medium ${status.className}`}>
            {status.label}
          </span>
        </div>
        <div className="flex items-end justify-between">
          <div>
            <div className="text-2xl font-bold text-white">{formatCurrency(account.currentBalance)}</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" />}
              {isPositive ? '+' : ''}{formatCurrency(account.totalGains)} ({account.totalGainsPercent.toFixed(2)}%)
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-slate-800/50 rounded-xl border border-slate-700 overflow-hidden">
      {/* Header with gradient */}
      <div className={`h-2 bg-gradient-to-r ${getProductColor(account.productType)}`} />

      <div className="p-5">
        {/* Top Row */}
        <div className="flex items-start justify-between mb-4">
          <div className="flex items-center gap-3">
            <div className={`w-12 h-12 rounded-xl bg-gradient-to-br ${getProductColor(account.productType)} flex items-center justify-center shadow-lg`}>
              <Wallet className="w-6 h-6 text-white" />
            </div>
            <div>
              <h3 className="font-semibold text-white text-lg">{account.productName}</h3>
              <div className="flex items-center gap-2">
                <span className="text-sm text-slate-400">{account.accountNumber}</span>
                <span className={`px-2 py-0.5 rounded text-xs font-medium ${status.className}`}>
                  {status.label}
                </span>
              </div>
            </div>
          </div>

          {showActions && (
            <div className="relative">
              <button
                onClick={() => setShowMenu(!showMenu)}
                className="p-2 text-slate-400 hover:text-white hover:bg-slate-700 rounded-lg transition-colors"
              >
                <MoreVertical className="w-5 h-5" />
              </button>
              {showMenu && (
                <div className="absolute right-0 top-full mt-1 w-48 bg-slate-800 border border-slate-700 rounded-lg shadow-xl z-10">
                  <button
                    onClick={() => {
                      setShowMenu(false);
                      onViewDetails?.(account.id);
                    }}
                    className="w-full flex items-center gap-2 px-4 py-2 text-sm text-slate-300 hover:bg-slate-700 transition-colors"
                  >
                    <Eye className="w-4 h-4" /> View Details
                  </button>
                  <button
                    onClick={() => {
                      setShowMenu(false);
                      onManageSettings?.(account.id);
                    }}
                    className="w-full flex items-center gap-2 px-4 py-2 text-sm text-slate-300 hover:bg-slate-700 transition-colors"
                  >
                    <Settings className="w-4 h-4" /> Account Settings
                  </button>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Balance */}
        <div className="mb-4">
          <div className="text-sm text-slate-400 mb-1">Current Balance</div>
          <div className="text-3xl font-bold text-white">{formatCurrency(account.currentBalance)}</div>
        </div>

        {/* Stats Grid */}
        <div className="grid grid-cols-2 gap-4 mb-4">
          {/* Total Gains */}
          <div className="p-3 bg-slate-900/50 rounded-lg">
            <div className="flex items-center gap-2 mb-1">
              {isPositive ? (
                <TrendingUp className="w-4 h-4 text-emerald-400" />
              ) : (
                <TrendingDown className="w-4 h-4 text-red-400" />
              )}
              <span className="text-xs text-slate-500">Total Gains</span>
            </div>
            <div className={`font-semibold ${isPositive ? 'text-emerald-400' : 'text-red-400'}`}>
              {isPositive ? '+' : ''}{formatCurrency(account.totalGains)}
            </div>
            <div className={`text-xs ${isPositive ? 'text-emerald-400/70' : 'text-red-400/70'}`}>
              {isPositive ? '+' : ''}{account.totalGainsPercent.toFixed(2)}%
            </div>
          </div>

          {/* Monthly Return */}
          <div className="p-3 bg-slate-900/50 rounded-lg">
            <div className="flex items-center gap-2 mb-1">
              <Percent className="w-4 h-4 text-blue-400" />
              <span className="text-xs text-slate-500">Monthly Return</span>
            </div>
            <div className={`font-semibold ${account.monthlyReturn >= 0 ? 'text-emerald-400' : 'text-red-400'}`}>
              {account.monthlyReturn >= 0 ? '+' : ''}{formatCurrency(account.monthlyReturn)}
            </div>
            <div className={`text-xs ${account.monthlyReturn >= 0 ? 'text-emerald-400/70' : 'text-red-400/70'}`}>
              {account.monthlyReturnPercent >= 0 ? '+' : ''}{account.monthlyReturnPercent.toFixed(2)}%
            </div>
          </div>
        </div>

        {/* Footer Info */}
        <div className="flex items-center justify-between text-xs text-slate-500 pt-3 border-t border-slate-700">
          <div className="flex items-center gap-1">
            <Calendar className="w-3.5 h-3.5" />
            <span>Opened {formatDate(account.createdAt)}</span>
          </div>
          <div className={`flex items-center gap-1 ${getRiskColor(account.riskLevel)}`}>
            <span className="capitalize">{account.riskLevel} Risk</span>
          </div>
        </div>

        {/* Next Distribution */}
        {account.nextDistributionDate && (
          <div className="mt-3 p-2 bg-blue-500/10 border border-blue-500/20 rounded-lg">
            <div className="flex items-center gap-2 text-xs text-blue-400">
              <Clock className="w-3.5 h-3.5" />
              <span>Next distribution: {formatDate(account.nextDistributionDate)}</span>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default AccountSummaryCard;
