'use client';

import { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import {
  Ghost, Bot, Zap, CheckCircle, AlertTriangle, Clock, TrendingUp,
  FileText, CreditCard, PiggyBank, Package, Brain, Eye, RefreshCw,
  ArrowRight, ChevronDown, ChevronUp, Activity, Shield, Sparkles,
  XCircle, CircleDot, Loader2, Mail, Landmark, AlertCircle, DollarSign
} from 'lucide-react';
import { InternalHeader } from '@/components/ui/internal-header';

interface DashboardData {
  executions: {
    active: number;
    completed: number;
    paused: number;
    failed: number;
    recent: Array<{
      id: string;
      orderNumber: string;
      currentStage: string;
      status: string;
      createdAt: string;
      humanInterventions: number;
      anomaliesDetected: number;
    }>;
  };
  actions: {
    recent: Array<{
      id: string;
      agentName: string;
      actionType: string;
      targetEntity: string;
      status: string;
      anomalyDetected: boolean;
      createdAt: string;
    }>;
    anomalyCount: number;
  };
  sniffChecks: {
    pending: number;
    approved: number;
    rejected: number;
    autoApproved: number;
  };
  selfMod: {
    pending: number;
    approved: number;
    rejected: number;
    implemented: number;
  };
  patterns: {
    total: number;
    significant: number;
  };
  metrics: {
    autonomousRate: number;
    totalExecutions: number;
  };
}

interface PendingSniffCheck {
  id: string;
  gateType: string;
  triggerReason: string;
  priority: string;
  entityType: string;
  entitySnapshot: Record<string, unknown>;
  proposedAction: Record<string, unknown>;
  createdAt: string;
}

interface PendingProposal {
  id: string;
  proposalType: string;
  title: string;
  description: string;
  rationale: string;
  targetSystem: string;
  riskLevel: string;
  confidence: number;
  createdAt: string;
}

const STAGE_ICONS: Record<string, typeof Clock> = {
  order_placed: Package,
  payment_processing: CreditCard,
  payment_confirmed: CheckCircle,
  invoice_generated: FileText,
  transaction_recorded: PiggyBank,
  ar_updated: TrendingUp,
  fulfilled: Package,
  cash_reconciled: CheckCircle,
  completed: CheckCircle,
};

const STATUS_COLORS: Record<string, string> = {
  active: 'text-brand bg-brand-deep/20',
  completed: 'text-green-400 bg-green-500/20',
  paused: 'text-yellow-400 bg-yellow-500/20',
  failed: 'text-red-400 bg-red-500/20',
};

const PRIORITY_COLORS: Record<string, string> = {
  low: 'text-gray-400 bg-gray-500/20',
  normal: 'text-blue-400 bg-blue-500/20',
  high: 'text-orange-400 bg-orange-500/20',
  critical: 'text-red-400 bg-red-500/20',
};

export default function OrderToCashDashboard() {
  const [data, setData] = useState<DashboardData | null>(null);
  const [sniffChecks, setSniffChecks] = useState<PendingSniffCheck[]>([]);
  const [proposals, setProposals] = useState<PendingProposal[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'overview' | 'sniff-checks' | 'self-mod' | 'actions' | 'dunning' | 'reconciliation' | 'inventory' | 'ap' | 'expenses'>('overview');
  const [dunningStats, setDunningStats] = useState<{
    totalOverdue: number;
    byLevel: { level: number; count: number; totalAmount: number }[];
    totalOverdueAmount: number;
    avgDaysOverdue: number;
  } | null>(null);
  const [reconStats, setReconStats] = useState<{
    totalReconciliations: number;
    matched: number;
    discrepancies: number;
    totalDiscrepancyAmount: number;
    pendingReview: number;
  } | null>(null);
  const [recentReconciliations, setRecentReconciliations] = useState<Array<{
    id: string;
    reconciliationId: string;
    stripePayoutId: string | null;
    expectedAmount: number;
    actualAmount: number;
    discrepancy: number;
    status: string;
    createdAt: string;
  }>>([]);
  const [inventoryStats, setInventoryStats] = useState<{
    totalAlerts: number;
    pending: number;
    ordered: number;
    critical: number;
    fulfilled: number;
  } | null>(null);
  const [apStats, setApStats] = useState<{
    totalPending: number;
    totalPendingAmount: number;
    overdueCount: number;
    overdueAmount: number;
    dueThisWeek: number;
    paidThisMonth: number;
  } | null>(null);
  const [expenseStats, setExpenseStats] = useState<{
    total: number;
    pending: number;
    categorized: number;
    flagged: number;
    reviewed: number;
  } | null>(null);
  const [expandedExecution, setExpandedExecution] = useState<string | null>(null);
  const [processing, setProcessing] = useState<string | null>(null);

  const fetchData = async () => {
    try {
      const [dashRes, sniffRes, propRes, dunningRes, reconStatsRes, reconRecentRes, invRes, apRes, expRes] = await Promise.all([
        fetch('/api/order-to-cash/dashboard'),
        fetch('/api/order-to-cash/sniff-checks'),
        fetch('/api/order-to-cash/self-mod'),
        fetch('/api/order-to-cash/dunning?action=stats'),
        fetch('/api/order-to-cash/reconciliation?action=stats'),
        fetch('/api/order-to-cash/reconciliation?action=recent'),
        fetch('/api/order-to-cash/inventory?action=stats'),
        fetch('/api/order-to-cash/ap?action=stats'),
        fetch('/api/order-to-cash/expenses?action=stats'),
      ]);

      const dashData = await dashRes.json();
      const sniffData = await sniffRes.json();
      const propData = await propRes.json();
      const dunningData = await dunningRes.json();
      const reconStatsData = await reconStatsRes.json();
      const reconRecentData = await reconRecentRes.json();
      const invData = await invRes.json();
      const apData = await apRes.json();
      const expData = await expRes.json();

      setData(dashData);
      setSniffChecks(sniffData.sniffChecks || []);
      setProposals(propData.proposals || []);
      setDunningStats(dunningData);
      setReconStats(reconStatsData);
      setRecentReconciliations(reconRecentData || []);
      setInventoryStats(invData);
      setApStats(apData);
      setExpenseStats(expData);
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    const interval = setInterval(fetchData, 10000); // Refresh every 10s
    return () => clearInterval(interval);
  }, []);

  const handleSniffCheckDecision = async (gateId: string, decision: 'approved' | 'rejected') => {
    setProcessing(gateId);
    try {
      await fetch('/api/order-to-cash/sniff-checks', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ gateId, decision, reviewedBy: 'human' }),
      });
      await fetchData();
    } catch (error) {
      console.error('Failed to process decision:', error);
    } finally {
      setProcessing(null);
    }
  };

  const handleProposalDecision = async (proposalId: string, decision: 'approve' | 'reject') => {
    setProcessing(proposalId);
    try {
      await fetch('/api/order-to-cash/self-mod', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ proposalId, decision, reviewedBy: 'human' }),
      });
      await fetchData();
    } catch (error) {
      console.error('Failed to process proposal:', error);
    } finally {
      setProcessing(null);
    }
  };

  const formatTime = (dateStr: string) => {
    const date = new Date(dateStr);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    
    if (diffMins < 1) return 'Just now';
    if (diffMins < 60) return `${diffMins}m ago`;
    if (diffHours < 24) return `${diffHours}h ago`;
    return date.toLocaleDateString();
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-brand-bg flex items-center justify-center">
        <Loader2 className="w-8 h-8 text-brand animate-spin" />
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-brand-bg">
      <InternalHeader />
      
      <div className="pt-20 p-6">
        <div className="max-w-7xl mx-auto space-y-6">
          {/* Header */}
          <div className="flex items-center justify-between">
            <div>
              <h1 className="text-3xl font-bold gradient-text flex items-center gap-3">
                <Ghost className="w-8 h-8" />
                Order-to-Cash Autonomous System
              </h1>
              <p className="text-gray-400 mt-1">End-to-end automated financial operations</p>
            </div>
            <button
              onClick={fetchData}
              className="px-4 py-2 bg-white/10 hover:bg-white/20 rounded-lg flex items-center gap-2 text-white transition-colors"
            >
              <RefreshCw className="w-4 h-4" />
              Refresh
            </button>
          </div>

          {/* Metrics Row */}
          <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
            <MetricCard
              icon={Activity}
              label="Autonomous Rate"
              value={`${data?.metrics.autonomousRate || 100}%`}
              color="cyan"
            />
            <MetricCard
              icon={CheckCircle}
              label="Completed"
              value={data?.executions.completed || 0}
              color="green"
            />
            <MetricCard
              icon={Clock}
              label="Active"
              value={data?.executions.active || 0}
              color="blue"
            />
            <MetricCard
              icon={Eye}
              label="Sniff Checks"
              value={data?.sniffChecks.pending || 0}
              color="yellow"
              alert={data?.sniffChecks.pending ? data.sniffChecks.pending > 0 : false}
            />
            <MetricCard
              icon={Brain}
              label="Self-Mod Proposals"
              value={data?.selfMod.pending || 0}
              color="purple"
              alert={data?.selfMod.pending ? data.selfMod.pending > 0 : false}
            />
            <MetricCard
              icon={Sparkles}
              label="Patterns Learned"
              value={data?.patterns.total || 0}
              color="pink"
            />
          </div>

          {/* Tabs */}
          <div className="flex gap-2 border-b border-white/10 pb-2">
            {(['overview', 'inventory', 'ap', 'expenses', 'dunning', 'reconciliation', 'sniff-checks', 'self-mod', 'actions'] as const).map(tab => (
              <button
                key={tab}
                onClick={() => setActiveTab(tab)}
                className={`px-3 py-2 rounded-t-lg transition-colors capitalize text-sm ${
                  activeTab === tab
                    ? 'bg-white/10 text-white'
                    : 'text-gray-400 hover:text-white'
                }`}
              >
                {tab.replace('-', ' ')}
                {tab === 'inventory' && (inventoryStats?.critical || 0) > 0 && (
                  <span className="ml-1 px-1.5 py-0.5 text-xs bg-red-500/20 text-red-400 rounded">
                    {inventoryStats?.critical}
                  </span>
                )}
                {tab === 'ap' && (apStats?.overdueCount || 0) > 0 && (
                  <span className="ml-1 px-1.5 py-0.5 text-xs bg-red-500/20 text-red-400 rounded">
                    {apStats?.overdueCount}
                  </span>
                )}
                {tab === 'expenses' && (expenseStats?.flagged || 0) > 0 && (
                  <span className="ml-1 px-1.5 py-0.5 text-xs bg-yellow-500/20 text-yellow-400 rounded">
                    {expenseStats?.flagged}
                  </span>
                )}
                {tab === 'dunning' && (dunningStats?.totalOverdue || 0) > 0 && (
                  <span className="ml-1 px-1.5 py-0.5 text-xs bg-orange-500/20 text-orange-400 rounded">
                    {dunningStats?.totalOverdue}
                  </span>
                )}
                {tab === 'reconciliation' && (reconStats?.discrepancies || 0) > 0 && (
                  <span className="ml-1 px-1.5 py-0.5 text-xs bg-red-500/20 text-red-400 rounded">
                    {reconStats?.discrepancies}
                  </span>
                )}
                {tab === 'sniff-checks' && (data?.sniffChecks.pending || 0) > 0 && (
                  <span className="ml-1 px-1.5 py-0.5 text-xs bg-yellow-500/20 text-yellow-400 rounded">
                    {data?.sniffChecks.pending}
                  </span>
                )}
                {tab === 'self-mod' && (data?.selfMod.pending || 0) > 0 && (
                  <span className="ml-1 px-1.5 py-0.5 text-xs bg-brand-secondary/20 text-brand-secondary-light rounded">
                    {data?.selfMod.pending}
                  </span>
                )}
              </button>
            ))}
          </div>

          {/* Tab Content */}
          <AnimatePresence mode="wait">
            {activeTab === 'overview' && (
              <motion.div
                key="overview"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="grid grid-cols-1 lg:grid-cols-2 gap-6"
              >
                {/* Recent Executions */}
                <div className="glass-card p-6 border border-white/10">
                  <h2 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                    <Zap className="w-5 h-5 text-brand" />
                    Recent Executions
                  </h2>
                  <div className="space-y-3">
                    {data?.executions.recent.length === 0 && (
                      <p className="text-gray-500 text-center py-4">No executions yet</p>
                    )}
                    {data?.executions.recent.map(exec => {
                      const StageIcon = STAGE_ICONS[exec.currentStage] || Clock;
                      return (
                        <div
                          key={exec.id}
                          className="p-4 bg-white/5 rounded-lg border border-white/5 hover:border-white/10 transition-colors"
                        >
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-3">
                              <StageIcon className="w-5 h-5 text-brand" />
                              <div>
                                <div className="text-white font-medium">{exec.orderNumber}</div>
                                <div className="text-xs text-gray-500">
                                  Stage: {exec.currentStage.replace(/_/g, ' ')}
                                </div>
                              </div>
                            </div>
                            <div className="flex items-center gap-2">
                              <span className={`px-2 py-1 rounded text-xs capitalize ${STATUS_COLORS[exec.status]}`}>
                                {exec.status}
                              </span>
                              {exec.anomaliesDetected > 0 && (
                                <span className="px-2 py-1 rounded text-xs bg-orange-500/20 text-orange-400">
                                  {exec.anomaliesDetected} anomaly
                                </span>
                              )}
                            </div>
                          </div>
                          <div className="mt-2 flex items-center gap-4 text-xs text-gray-500">
                            <span>{formatTime(exec.createdAt)}</span>
                            <span>• {exec.humanInterventions} human interventions</span>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                </div>

                {/* Recent Agent Actions */}
                <div className="glass-card p-6 border border-white/10">
                  <h2 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                    <Bot className="w-5 h-5 text-brand-secondary-light" />
                    Agent Activity Stream
                  </h2>
                  <div className="space-y-2 max-h-96 overflow-y-auto">
                    {data?.actions.recent.length === 0 && (
                      <p className="text-gray-500 text-center py-4">No agent actions yet</p>
                    )}
                    {data?.actions.recent.map(action => (
                      <div
                        key={action.id}
                        className={`p-3 rounded-lg flex items-center gap-3 ${
                          action.anomalyDetected ? 'bg-orange-500/10 border border-orange-500/20' : 'bg-white/5'
                        }`}
                      >
                        <CircleDot className={`w-4 h-4 ${
                          action.status === 'completed' ? 'text-green-400' :
                          action.status === 'failed' ? 'text-red-400' : 'text-gray-400'
                        }`} />
                        <div className="flex-1 min-w-0">
                          <div className="text-sm text-white truncate">
                            <span className="text-brand">{action.agentName}</span>
                            {' '}&rarr; {action.actionType.replace(/_/g, ' ')}
                          </div>
                          <div className="text-xs text-gray-500">
                            {action.targetEntity} • {formatTime(action.createdAt)}
                          </div>
                        </div>
                        {action.anomalyDetected && (
                          <AlertTriangle className="w-4 h-4 text-orange-400" />
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              </motion.div>
            )}

            {activeTab === 'sniff-checks' && (
              <motion.div
                key="sniff-checks"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-4"
              >
                <div className="glass-card p-6 border border-white/10">
                  <h2 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                    <Eye className="w-5 h-5 text-yellow-400" />
                    Pending Sniff Checks
                    <span className="text-sm font-normal text-gray-400">
                      (Human verification required)
                    </span>
                  </h2>
                  
                  {sniffChecks.length === 0 ? (
                    <div className="text-center py-8">
                      <Shield className="w-12 h-12 text-green-400 mx-auto mb-3" />
                      <p className="text-gray-400">All clear! No items require human review.</p>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {sniffChecks.map(check => (
                        <div
                          key={check.id}
                          className={`p-4 rounded-lg border ${
                            check.priority === 'critical' ? 'border-red-500/30 bg-red-500/5' :
                            check.priority === 'high' ? 'border-orange-500/30 bg-orange-500/5' :
                            'border-white/10 bg-white/5'
                          }`}
                        >
                          <div className="flex items-start justify-between gap-4">
                            <div>
                              <div className="flex items-center gap-2 mb-2">
                                <span className={`px-2 py-1 rounded text-xs uppercase ${PRIORITY_COLORS[check.priority]}`}>
                                  {check.priority}
                                </span>
                                <span className="text-white font-medium">{check.triggerReason}</span>
                              </div>
                              <div className="text-sm text-gray-400 mb-2">
                                Entity: {check.entityType} • Type: {check.gateType.replace(/_/g, ' ')}
                              </div>
                              <pre className="text-xs bg-black/30 p-2 rounded overflow-x-auto">
                                {JSON.stringify(check.entitySnapshot, null, 2)}
                              </pre>
                            </div>
                            <div className="flex gap-2 shrink-0">
                              <button
                                onClick={() => handleSniffCheckDecision(check.id, 'rejected')}
                                disabled={processing === check.id}
                                className="px-3 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg flex items-center gap-1 transition-colors disabled:opacity-50"
                              >
                                {processing === check.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <XCircle className="w-4 h-4" />}
                                Reject
                              </button>
                              <button
                                onClick={() => handleSniffCheckDecision(check.id, 'approved')}
                                disabled={processing === check.id}
                                className="px-3 py-2 bg-green-500/20 hover:bg-green-500/30 text-green-400 rounded-lg flex items-center gap-1 transition-colors disabled:opacity-50"
                              >
                                {processing === check.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle className="w-4 h-4" />}
                                Approve
                              </button>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </motion.div>
            )}

            {activeTab === 'self-mod' && (
              <motion.div
                key="self-mod"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-4"
              >
                <div className="glass-card p-6 border border-white/10">
                  <h2 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                    <Brain className="w-5 h-5 text-brand-secondary-light" />
                    Self-Modification Proposals
                    <span className="text-sm font-normal text-gray-400">
                      (System improvement suggestions)
                    </span>
                  </h2>
                  
                  {proposals.length === 0 ? (
                    <div className="text-center py-8">
                      <Sparkles className="w-12 h-12 text-brand-secondary-light mx-auto mb-3" />
                      <p className="text-gray-400">No pending proposals. The system is learning patterns...</p>
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {proposals.map(proposal => (
                        <div
                          key={proposal.id}
                          className="p-4 rounded-lg border border-brand-secondary/20 bg-brand-secondary/5"
                        >
                          <div className="flex items-start justify-between gap-4">
                            <div className="flex-1">
                              <div className="flex items-center gap-2 mb-2">
                                <span className={`px-2 py-1 rounded text-xs uppercase ${
                                  proposal.riskLevel === 'low' ? 'bg-green-500/20 text-green-400' :
                                  proposal.riskLevel === 'medium' ? 'bg-yellow-500/20 text-yellow-400' :
                                  'bg-red-500/20 text-red-400'
                                }`}>
                                  {proposal.riskLevel} risk
                                </span>
                                <span className="text-white font-medium">{proposal.title}</span>
                              </div>
                              <p className="text-sm text-gray-300 mb-2">{proposal.description}</p>
                              <p className="text-xs text-gray-500 mb-2">
                                <span className="text-brand-secondary-light">Rationale:</span> {proposal.rationale}
                              </p>
                              <div className="text-xs text-gray-500">
                                Target: {proposal.targetSystem} • Confidence: {(proposal.confidence * 100).toFixed(0)}%
                              </div>
                            </div>
                            <div className="flex gap-2 shrink-0">
                              <button
                                onClick={() => handleProposalDecision(proposal.id, 'reject')}
                                disabled={processing === proposal.id}
                                className="px-3 py-2 bg-red-500/20 hover:bg-red-500/30 text-red-400 rounded-lg flex items-center gap-1 transition-colors disabled:opacity-50"
                              >
                                {processing === proposal.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <XCircle className="w-4 h-4" />}
                                Reject
                              </button>
                              <button
                                onClick={() => handleProposalDecision(proposal.id, 'approve')}
                                disabled={processing === proposal.id}
                                className="px-3 py-2 bg-brand-secondary/20 hover:bg-brand-secondary/30 text-brand-secondary-light rounded-lg flex items-center gap-1 transition-colors disabled:opacity-50"
                              >
                                {processing === proposal.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <CheckCircle className="w-4 h-4" />}
                                Implement
                              </button>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </motion.div>
            )}

            {activeTab === 'actions' && (
              <motion.div
                key="actions"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
              >
                <div className="glass-card p-6 border border-white/10">
                  <h2 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                    <Bot className="w-5 h-5 text-brand" />
                    All Agent Actions
                  </h2>
                  <div className="space-y-2">
                    {data?.actions.recent.map(action => (
                      <div
                        key={action.id}
                        className={`p-4 rounded-lg ${
                          action.anomalyDetected ? 'bg-orange-500/10 border border-orange-500/20' : 'bg-white/5'
                        }`}
                      >
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-3">
                            <div className={`w-2 h-2 rounded-full ${
                              action.status === 'completed' ? 'bg-green-400' :
                              action.status === 'failed' ? 'bg-red-400' : 'bg-gray-400'
                            }`} />
                            <span className="text-brand font-medium">{action.agentName}</span>
                            <ArrowRight className="w-4 h-4 text-gray-500" />
                            <span className="text-white">{action.actionType.replace(/_/g, ' ')}</span>
                          </div>
                          <div className="flex items-center gap-3">
                            <span className="text-sm text-gray-500">{action.targetEntity}</span>
                            <span className="text-xs text-gray-500">{formatTime(action.createdAt)}</span>
                            {action.anomalyDetected && (
                              <AlertTriangle className="w-4 h-4 text-orange-400" />
                            )}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </motion.div>
            )}

            {/* Dunning Tab */}
            {activeTab === 'dunning' && (
              <motion.div
                key="dunning"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-6"
              >
                {/* Dunning Stats */}
                <div className="grid grid-cols-4 gap-4">
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <Mail className="w-8 h-8 text-orange-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">{dunningStats?.totalOverdue || 0}</p>
                        <p className="text-sm text-gray-400">Total Overdue</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <DollarSign className="w-8 h-8 text-red-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">${(dunningStats?.totalOverdueAmount || 0).toFixed(2)}</p>
                        <p className="text-sm text-gray-400">Amount Overdue</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <Clock className="w-8 h-8 text-yellow-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">{Math.round(dunningStats?.avgDaysOverdue || 0)}</p>
                        <p className="text-sm text-gray-400">Avg Days Overdue</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <button
                      onClick={async () => {
                        setProcessing('dunning');
                        await fetch('/api/order-to-cash/dunning', { method: 'POST', body: JSON.stringify({ autoSendEmails: true }), headers: { 'Content-Type': 'application/json' } });
                        await fetchData();
                        setProcessing(null);
                      }}
                      disabled={processing === 'dunning'}
                      className="w-full h-full flex items-center justify-center gap-2 text-brand hover:text-brand-light transition-colors"
                    >
                      {processing === 'dunning' ? <Loader2 className="w-5 h-5 animate-spin" /> : <RefreshCw className="w-5 h-5" />}
                      <span>Run Dunning</span>
                    </button>
                  </div>
                </div>

                {/* Dunning by Level */}
                <div className="glass-card p-6 rounded-xl">
                  <h3 className="text-lg font-semibold text-white mb-4">Overdue by Dunning Level</h3>
                  <div className="space-y-3">
                    {(dunningStats?.byLevel || []).map(level => (
                      <div key={level.level} className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
                        <div className="flex items-center gap-3">
                          <div className={`w-3 h-3 rounded-full ${
                            level.level === 0 ? 'bg-gray-400' :
                            level.level === 1 ? 'bg-yellow-400' :
                            level.level === 2 ? 'bg-orange-400' : 'bg-red-400'
                          }`} />
                          <span className="text-white">
                            {level.level === 0 ? 'Not Yet Dunned' :
                             level.level === 1 ? 'Level 1 - Reminder (7+ days)' :
                             level.level === 2 ? 'Level 2 - Warning (14+ days)' :
                             'Level 3 - Final Notice (30+ days)'}
                          </span>
                        </div>
                        <div className="flex items-center gap-6">
                          <span className="text-gray-400">{level.count} invoices</span>
                          <span className={`font-semibold ${
                            level.level === 3 ? 'text-red-400' :
                            level.level === 2 ? 'text-orange-400' :
                            level.level === 1 ? 'text-yellow-400' : 'text-gray-400'
                          }`}>
                            ${level.totalAmount.toFixed(2)}
                          </span>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </motion.div>
            )}

            {/* Reconciliation Tab */}
            {activeTab === 'reconciliation' && (
              <motion.div
                key="reconciliation"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-6"
              >
                {/* Reconciliation Stats */}
                <div className="grid grid-cols-5 gap-4">
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <Landmark className="w-8 h-8 text-brand" />
                      <div>
                        <p className="text-2xl font-bold text-white">{reconStats?.totalReconciliations || 0}</p>
                        <p className="text-sm text-gray-400">Total</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <CheckCircle className="w-8 h-8 text-green-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">{reconStats?.matched || 0}</p>
                        <p className="text-sm text-gray-400">Matched</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <AlertCircle className="w-8 h-8 text-red-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">{reconStats?.discrepancies || 0}</p>
                        <p className="text-sm text-gray-400">Discrepancies</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <DollarSign className="w-8 h-8 text-orange-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">${(reconStats?.totalDiscrepancyAmount || 0).toFixed(2)}</p>
                        <p className="text-sm text-gray-400">Discrepancy $</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <button
                      onClick={async () => {
                        setProcessing('reconciliation');
                        await fetch('/api/order-to-cash/reconciliation', { method: 'POST', body: JSON.stringify({ action: 'run' }), headers: { 'Content-Type': 'application/json' } });
                        await fetchData();
                        setProcessing(null);
                      }}
                      disabled={processing === 'reconciliation'}
                      className="w-full h-full flex items-center justify-center gap-2 text-brand hover:text-brand-light transition-colors"
                    >
                      {processing === 'reconciliation' ? <Loader2 className="w-5 h-5 animate-spin" /> : <RefreshCw className="w-5 h-5" />}
                      <span>Run Reconciliation</span>
                    </button>
                  </div>
                </div>

                {/* Recent Reconciliations */}
                <div className="glass-card p-6 rounded-xl">
                  <h3 className="text-lg font-semibold text-white mb-4">Recent Reconciliations</h3>
                  <div className="space-y-3">
                    {recentReconciliations.length === 0 ? (
                      <p className="text-gray-500 text-center py-8">No reconciliations yet. Click "Run Reconciliation" to process payouts.</p>
                    ) : (
                      recentReconciliations.map(recon => (
                        <div key={recon.id} className={`p-4 rounded-lg ${
                          recon.status === 'discrepancy' ? 'bg-red-500/10 border border-red-500/20' :
                          recon.status === 'matched' ? 'bg-green-500/10 border border-green-500/20' :
                          'bg-white/5'
                        }`}>
                          <div className="flex items-center justify-between">
                            <div className="flex items-center gap-4">
                              <div className={`w-3 h-3 rounded-full ${
                                recon.status === 'matched' ? 'bg-green-400' :
                                recon.status === 'discrepancy' ? 'bg-red-400' :
                                recon.status === 'partial' ? 'bg-yellow-400' : 'bg-gray-400'
                              }`} />
                              <span className="text-brand font-mono text-sm">{recon.stripePayoutId || 'N/A'}</span>
                            </div>
                            <div className="flex items-center gap-6">
                              <div className="text-right">
                                <p className="text-sm text-gray-400">Expected</p>
                                <p className="text-white">${recon.expectedAmount.toFixed(2)}</p>
                              </div>
                              <div className="text-right">
                                <p className="text-sm text-gray-400">Actual</p>
                                <p className="text-white">${recon.actualAmount.toFixed(2)}</p>
                              </div>
                              {recon.discrepancy > 0 && (
                                <div className="text-right">
                                  <p className="text-sm text-gray-400">Discrepancy</p>
                                  <p className="text-red-400">${recon.discrepancy.toFixed(2)}</p>
                                </div>
                              )}
                              <span className={`px-2 py-1 text-xs rounded ${
                                recon.status === 'matched' ? 'bg-green-500/20 text-green-400' :
                                recon.status === 'discrepancy' ? 'bg-red-500/20 text-red-400' :
                                'bg-gray-500/20 text-gray-400'
                              }`}>
                                {recon.status}
                              </span>
                            </div>
                          </div>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              </motion.div>
            )}

            {/* Inventory Tab */}
            {activeTab === 'inventory' && (
              <motion.div
                key="inventory"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-6"
              >
                <div className="grid grid-cols-5 gap-4">
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <Package className="w-8 h-8 text-brand" />
                      <div>
                        <p className="text-2xl font-bold text-white">{inventoryStats?.totalAlerts || 0}</p>
                        <p className="text-sm text-gray-400">Total Alerts</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <AlertTriangle className="w-8 h-8 text-red-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">{inventoryStats?.critical || 0}</p>
                        <p className="text-sm text-gray-400">Critical</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <Clock className="w-8 h-8 text-yellow-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">{inventoryStats?.pending || 0}</p>
                        <p className="text-sm text-gray-400">Pending</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <CheckCircle className="w-8 h-8 text-green-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">{inventoryStats?.fulfilled || 0}</p>
                        <p className="text-sm text-gray-400">Fulfilled</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <button
                      onClick={async () => {
                        setProcessing('inventory');
                        await fetch('/api/order-to-cash/inventory', { method: 'POST', body: JSON.stringify({ action: 'check' }), headers: { 'Content-Type': 'application/json' } });
                        await fetchData();
                        setProcessing(null);
                      }}
                      disabled={processing === 'inventory'}
                      className="w-full h-full flex items-center justify-center gap-2 text-brand hover:text-brand-light transition-colors"
                    >
                      {processing === 'inventory' ? <Loader2 className="w-5 h-5 animate-spin" /> : <RefreshCw className="w-5 h-5" />}
                      <span>Check Levels</span>
                    </button>
                  </div>
                </div>
                <div className="glass-card p-6 rounded-xl">
                  <h3 className="text-lg font-semibold text-white mb-4">Inventory Alerts</h3>
                  <p className="text-gray-500 text-center py-8">Inventory monitoring active. Alerts will appear when stock falls below thresholds.</p>
                </div>
              </motion.div>
            )}

            {/* AP Tab */}
            {activeTab === 'ap' && (
              <motion.div
                key="ap"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-6"
              >
                <div className="grid grid-cols-5 gap-4">
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <FileText className="w-8 h-8 text-brand" />
                      <div>
                        <p className="text-2xl font-bold text-white">{apStats?.totalPending || 0}</p>
                        <p className="text-sm text-gray-400">Pending</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <DollarSign className="w-8 h-8 text-yellow-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">${((apStats?.totalPendingAmount || 0) / 1000).toFixed(1)}k</p>
                        <p className="text-sm text-gray-400">Pending $</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <AlertCircle className="w-8 h-8 text-red-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">{apStats?.overdueCount || 0}</p>
                        <p className="text-sm text-gray-400">Overdue</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <Clock className="w-8 h-8 text-orange-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">{apStats?.dueThisWeek || 0}</p>
                        <p className="text-sm text-gray-400">Due This Week</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <button
                      onClick={async () => {
                        setProcessing('ap');
                        await fetch('/api/order-to-cash/ap', { method: 'POST', body: JSON.stringify({ action: 'check-overdue' }), headers: { 'Content-Type': 'application/json' } });
                        await fetchData();
                        setProcessing(null);
                      }}
                      disabled={processing === 'ap'}
                      className="w-full h-full flex items-center justify-center gap-2 text-brand hover:text-brand-light transition-colors"
                    >
                      {processing === 'ap' ? <Loader2 className="w-5 h-5 animate-spin" /> : <RefreshCw className="w-5 h-5" />}
                      <span>Check Overdue</span>
                    </button>
                  </div>
                </div>
                <div className="glass-card p-6 rounded-xl">
                  <h3 className="text-lg font-semibold text-white mb-4">Accounts Payable</h3>
                  <p className="text-gray-500 text-center py-8">AP automation active. Create vendor invoices to start tracking payables.</p>
                </div>
              </motion.div>
            )}

            {/* Expenses Tab */}
            {activeTab === 'expenses' && (
              <motion.div
                key="expenses"
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -10 }}
                className="space-y-6"
              >
                <div className="grid grid-cols-5 gap-4">
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <CreditCard className="w-8 h-8 text-brand" />
                      <div>
                        <p className="text-2xl font-bold text-white">{expenseStats?.total || 0}</p>
                        <p className="text-sm text-gray-400">Total</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <Brain className="w-8 h-8 text-brand-secondary-light" />
                      <div>
                        <p className="text-2xl font-bold text-white">{expenseStats?.categorized || 0}</p>
                        <p className="text-sm text-gray-400">AI Categorized</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <AlertTriangle className="w-8 h-8 text-yellow-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">{expenseStats?.flagged || 0}</p>
                        <p className="text-sm text-gray-400">Needs Review</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <div className="flex items-center gap-3">
                      <CheckCircle className="w-8 h-8 text-green-400" />
                      <div>
                        <p className="text-2xl font-bold text-white">{expenseStats?.reviewed || 0}</p>
                        <p className="text-sm text-gray-400">Reviewed</p>
                      </div>
                    </div>
                  </div>
                  <div className="glass-card p-4 rounded-xl">
                    <button
                      onClick={async () => {
                        setProcessing('expenses');
                        await fetch('/api/order-to-cash/expenses', { method: 'POST', body: JSON.stringify({ action: 'bulk-categorize' }), headers: { 'Content-Type': 'application/json' } });
                        await fetchData();
                        setProcessing(null);
                      }}
                      disabled={processing === 'expenses'}
                      className="w-full h-full flex items-center justify-center gap-2 text-brand hover:text-brand-light transition-colors"
                    >
                      {processing === 'expenses' ? <Loader2 className="w-5 h-5 animate-spin" /> : <Brain className="w-5 h-5" />}
                      <span>Auto-Categorize</span>
                    </button>
                  </div>
                </div>
                <div className="glass-card p-6 rounded-xl">
                  <h3 className="text-lg font-semibold text-white mb-4">Expense Categorization</h3>
                  <p className="text-gray-500 text-center py-8">LLM-powered expense categorization active. Add expenses to see AI classification.</p>
                </div>
              </motion.div>
            )}
          </AnimatePresence>
        </div>
      </div>
    </div>
  );
}

function MetricCard({
  icon: Icon,
  label,
  value,
  color,
  alert = false,
}: {
  icon: typeof Clock;
  label: string;
  value: string | number;
  color: string;
  alert?: boolean;
}) {
  const colors: Record<string, string> = {
    cyan: 'text-brand bg-brand-deep/10 border-brand-deep/20',
    green: 'text-green-400 bg-green-500/10 border-green-500/20',
    blue: 'text-blue-400 bg-blue-500/10 border-blue-500/20',
    yellow: 'text-yellow-400 bg-yellow-500/10 border-yellow-500/20',
    purple: 'text-brand-secondary-light bg-brand-secondary/10 border-brand-secondary/20',
    pink: 'text-pink-400 bg-pink-500/10 border-pink-500/20',
  };

  return (
    <div className={`p-4 rounded-lg border ${colors[color]} ${alert ? 'animate-pulse' : ''}`}>
      <Icon className={`w-5 h-5 mb-2 ${colors[color].split(' ')[0]}`} />
      <div className="text-2xl font-bold text-white">{value}</div>
      <div className="text-xs text-gray-400">{label}</div>
    </div>
  );
}
