'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Ghost, Bot, Package, FileText, DollarSign, Mail, Zap, RefreshCw,
  CheckCircle, AlertTriangle, Clock, TrendingUp, Activity, Brain,
  Loader2, ArrowRight, Landmark, AlertCircle, Sparkles, Send
} from 'lucide-react';
import { InternalHeader } from '@/components/ui/internal-header';
import Link from 'next/link';

interface AutonomyStats {
  inventory: {
    totalProducts: number;
    lowStock: number;
    outOfStock: number;
    pendingAlerts: number;
    orderedAlerts: number;
  };
  ap: {
    pendingApproval: number;
    pendingAmount: number;
    scheduledPayments: number;
    overdueCount: number;
    paidThisMonth: number;
  };
  expenses: {
    totalExpenses: number;
    categorized: number;
    uncategorized: number;
    flagged: number;
    avgConfidence: number;
  };
  dunning: {
    totalOverdue: number;
    totalOverdueAmount: number;
  };
  reconciliation: {
    discrepancies: number;
    totalDiscrepancyAmount: number;
  };
}

export default function AutonomyDashboard() {
  const [stats, setStats] = useState<AutonomyStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [processing, setProcessing] = useState<string | null>(null);
  const [briefSending, setBriefSending] = useState(false);
  const [briefSent, setBriefSent] = useState(false);
  
  const fetchStats = async () => {
    try {
      const [inventoryRes, apRes, expensesRes, dunningRes, reconRes] = await Promise.all([
        fetch('/api/order-to-cash/inventory?action=stats'),
        fetch('/api/order-to-cash/ap?action=stats'),
        fetch('/api/order-to-cash/expenses?action=stats'),
        fetch('/api/order-to-cash/dunning?action=stats'),
        fetch('/api/order-to-cash/reconciliation?action=stats'),
      ]);
      
      const [inventory, ap, expenses, dunning, reconciliation] = await Promise.all([
        inventoryRes.json(),
        apRes.json(),
        expensesRes.json(),
        dunningRes.json(),
        reconRes.json(),
      ]);
      
      setStats({
        inventory,
        ap,
        expenses,
        dunning,
        reconciliation,
      });
    } catch (error) {
      console.error('Failed to fetch stats:', error);
    } finally {
      setLoading(false);
    }
  };
  
  useEffect(() => {
    fetchStats();
    const interval = setInterval(fetchStats, 30000);
    return () => clearInterval(interval);
  }, []);
  
  const runAction = async (action: string, endpoint: string, body: Record<string, unknown>) => {
    setProcessing(action);
    try {
      await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      await fetchStats();
    } catch (error) {
      console.error(`Failed to run ${action}:`, error);
    } finally {
      setProcessing(null);
    }
  };
  
  const sendBrief = async () => {
    setBriefSending(true);
    try {
      const res = await fetch('/api/order-to-cash/brief', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'send' }),
      });
      const data = await res.json();
      if (data.success) {
        setBriefSent(true);
        setTimeout(() => setBriefSent(false), 3000);
      }
    } catch (error) {
      console.error('Failed to send brief:', error);
    } finally {
      setBriefSending(false);
    }
  };
  
  if (loading) {
    return (
      <div className="min-h-screen bg-brand-bg">
        <InternalHeader />
        <div className="flex items-center justify-center h-96">
          <Loader2 className="w-8 h-8 text-brand animate-spin" />
        </div>
      </div>
    );
  }
  
  const totalAlerts = (stats?.inventory.outOfStock || 0) + 
                      (stats?.ap.overdueCount || 0) + 
                      (stats?.expenses.flagged || 0) + 
                      (stats?.dunning.totalOverdue || 0) +
                      (stats?.reconciliation.discrepancies || 0);
  
  return (
    <div className="min-h-screen bg-brand-bg">
      <InternalHeader />
      
      <div className="max-w-7xl mx-auto px-6 py-8">
        {/* Header */}
        <div className="flex items-center justify-between mb-8">
          <div>
            <h1 className="text-3xl font-bold text-white flex items-center gap-3">
              <Ghost className="w-8 h-8 text-brand" />
              Full Autonomy Status
            </h1>
            <p className="text-gray-400 mt-1">All systems operating autonomously</p>
          </div>
          
          <div className="flex items-center gap-4">
            <button
              onClick={sendBrief}
              disabled={briefSending}
              className="flex items-center gap-2 px-4 py-2 bg-brand-secondary-deep hover:bg-brand-secondary text-white rounded-lg transition-colors disabled:opacity-50"
            >
              {briefSending ? <Loader2 className="w-4 h-4 animate-spin" /> : 
               briefSent ? <CheckCircle className="w-4 h-4" /> : <Send className="w-4 h-4" />}
              {briefSent ? 'Sent!' : 'Send Weekly Brief'}
            </button>
            
            <button
              onClick={fetchStats}
              className="p-2 text-gray-400 hover:text-white transition-colors"
            >
              <RefreshCw className="w-5 h-5" />
            </button>
          </div>
        </div>
        
        {/* Alert Banner */}
        {totalAlerts > 0 && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            className="bg-orange-500/10 border border-orange-500/30 rounded-xl p-4 mb-6 flex items-center justify-between"
          >
            <div className="flex items-center gap-3">
              <AlertTriangle className="w-5 h-5 text-orange-400" />
              <span className="text-orange-300">
                {totalAlerts} items require attention across all modules
              </span>
            </div>
            <Link
              href="/ghost-control/order-to-cash"
              className="text-orange-400 hover:text-orange-300 flex items-center gap-1 text-sm"
            >
              View Details <ArrowRight className="w-4 h-4" />
            </Link>
          </motion.div>
        )}
        
        {/* Module Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {/* Inventory Module */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.1 }}
            className="glass-card p-6 rounded-xl"
          >
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <Package className="w-6 h-6 text-blue-400" />
                <h3 className="text-lg font-semibold text-white">Inventory</h3>
              </div>
              {(stats?.inventory.outOfStock || 0) > 0 && (
                <span className="px-2 py-1 text-xs bg-red-500/20 text-red-400 rounded">
                  {stats?.inventory.outOfStock} critical
                </span>
              )}
            </div>
            
            <div className="space-y-3 mb-4">
              <div className="flex justify-between">
                <span className="text-gray-400">Products</span>
                <span className="text-white">{stats?.inventory.totalProducts || 0}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">Low Stock</span>
                <span className={stats?.inventory.lowStock ? 'text-yellow-400' : 'text-white'}>
                  {stats?.inventory.lowStock || 0}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">Pending Reorders</span>
                <span className="text-white">{stats?.inventory.orderedAlerts || 0}</span>
              </div>
            </div>
            
            <button
              onClick={() => runAction('inventory', '/api/order-to-cash/inventory', { action: 'auto-reorder' })}
              disabled={processing === 'inventory'}
              className="w-full py-2 bg-blue-600/20 hover:bg-blue-600/30 text-blue-400 rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              {processing === 'inventory' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4" />}
              Run Auto-Reorder
            </button>
          </motion.div>
          
          {/* Accounts Payable Module */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.2 }}
            className="glass-card p-6 rounded-xl"
          >
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <FileText className="w-6 h-6 text-green-400" />
                <h3 className="text-lg font-semibold text-white">Accounts Payable</h3>
              </div>
              {(stats?.ap.overdueCount || 0) > 0 && (
                <span className="px-2 py-1 text-xs bg-red-500/20 text-red-400 rounded">
                  {stats?.ap.overdueCount} overdue
                </span>
              )}
            </div>
            
            <div className="space-y-3 mb-4">
              <div className="flex justify-between">
                <span className="text-gray-400">Pending Approval</span>
                <span className="text-white">{stats?.ap.pendingApproval || 0}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">Pending Amount</span>
                <span className="text-white">${(stats?.ap.pendingAmount || 0).toFixed(2)}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">Scheduled</span>
                <span className="text-white">{stats?.ap.scheduledPayments || 0}</span>
              </div>
            </div>
            
            <button
              onClick={() => runAction('ap', '/api/order-to-cash/ap', { action: 'process-payments' })}
              disabled={processing === 'ap'}
              className="w-full py-2 bg-green-600/20 hover:bg-green-600/30 text-green-400 rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              {processing === 'ap' ? <Loader2 className="w-4 h-4 animate-spin" /> : <DollarSign className="w-4 h-4" />}
              Process Payments
            </button>
          </motion.div>
          
          {/* Expense Intelligence Module */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.3 }}
            className="glass-card p-6 rounded-xl"
          >
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <Brain className="w-6 h-6 text-brand-secondary-light" />
                <h3 className="text-lg font-semibold text-white">Expense AI</h3>
              </div>
              {(stats?.expenses.flagged || 0) > 0 && (
                <span className="px-2 py-1 text-xs bg-yellow-500/20 text-yellow-400 rounded">
                  {stats?.expenses.flagged} flagged
                </span>
              )}
            </div>
            
            <div className="space-y-3 mb-4">
              <div className="flex justify-between">
                <span className="text-gray-400">Categorized</span>
                <span className="text-white">{stats?.expenses.categorized || 0}</span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">Pending Review</span>
                <span className={stats?.expenses.uncategorized ? 'text-yellow-400' : 'text-white'}>
                  {stats?.expenses.uncategorized || 0}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">AI Confidence</span>
                <span className="text-white">{((stats?.expenses.avgConfidence || 0) * 100).toFixed(0)}%</span>
              </div>
            </div>
            
            <button
              onClick={() => runAction('expenses', '/api/order-to-cash/expenses', { action: 'process-all' })}
              disabled={processing === 'expenses'}
              className="w-full py-2 bg-brand-secondary-deep/20 hover:bg-brand-secondary-deep/30 text-brand-secondary-light rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              {processing === 'expenses' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
              Categorize All
            </button>
          </motion.div>
          
          {/* AR Dunning Module */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.4 }}
            className="glass-card p-6 rounded-xl"
          >
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <Mail className="w-6 h-6 text-orange-400" />
                <h3 className="text-lg font-semibold text-white">AR Dunning</h3>
              </div>
              {(stats?.dunning.totalOverdue || 0) > 0 && (
                <span className="px-2 py-1 text-xs bg-orange-500/20 text-orange-400 rounded">
                  {stats?.dunning.totalOverdue} overdue
                </span>
              )}
            </div>
            
            <div className="space-y-3 mb-4">
              <div className="flex justify-between">
                <span className="text-gray-400">Overdue Invoices</span>
                <span className={stats?.dunning.totalOverdue ? 'text-orange-400' : 'text-white'}>
                  {stats?.dunning.totalOverdue || 0}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">Overdue Amount</span>
                <span className="text-white">${(stats?.dunning.totalOverdueAmount || 0).toFixed(2)}</span>
              </div>
            </div>
            
            <button
              onClick={() => runAction('dunning', '/api/order-to-cash/dunning', { autoSendEmails: true })}
              disabled={processing === 'dunning'}
              className="w-full py-2 bg-orange-600/20 hover:bg-orange-600/30 text-orange-400 rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              {processing === 'dunning' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Mail className="w-4 h-4" />}
              Run Dunning
            </button>
          </motion.div>
          
          {/* Bank Reconciliation Module */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.5 }}
            className="glass-card p-6 rounded-xl"
          >
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center gap-3">
                <Landmark className="w-6 h-6 text-brand" />
                <h3 className="text-lg font-semibold text-white">Bank Recon</h3>
              </div>
              {(stats?.reconciliation.discrepancies || 0) > 0 && (
                <span className="px-2 py-1 text-xs bg-red-500/20 text-red-400 rounded">
                  {stats?.reconciliation.discrepancies} issues
                </span>
              )}
            </div>
            
            <div className="space-y-3 mb-4">
              <div className="flex justify-between">
                <span className="text-gray-400">Discrepancies</span>
                <span className={stats?.reconciliation.discrepancies ? 'text-red-400' : 'text-white'}>
                  {stats?.reconciliation.discrepancies || 0}
                </span>
              </div>
              <div className="flex justify-between">
                <span className="text-gray-400">Discrepancy $</span>
                <span className="text-white">${(stats?.reconciliation.totalDiscrepancyAmount || 0).toFixed(2)}</span>
              </div>
            </div>
            
            <button
              onClick={() => runAction('reconciliation', '/api/order-to-cash/reconciliation', { action: 'run' })}
              disabled={processing === 'reconciliation'}
              className="w-full py-2 bg-brand-deep/20 hover:bg-brand-deep/30 text-brand rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              {processing === 'reconciliation' ? <Loader2 className="w-4 h-4 animate-spin" /> : <Activity className="w-4 h-4" />}
              Run Reconciliation
            </button>
          </motion.div>
          
          {/* Order-to-Cash Link */}
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: 0.6 }}
            className="glass-card p-6 rounded-xl border border-brand-deep/30"
          >
            <div className="flex items-center gap-3 mb-4">
              <Bot className="w-6 h-6 text-brand" />
              <h3 className="text-lg font-semibold text-white">Order-to-Cash</h3>
            </div>
            
            <p className="text-gray-400 text-sm mb-4">
              Full autonomous pipeline: Order → Payment → Invoice → Transaction → AR → Bank
            </p>
            
            <Link
              href="/ghost-control/order-to-cash"
              className="w-full py-2 bg-brand-deep hover:bg-brand-deep text-white rounded-lg transition-colors flex items-center justify-center gap-2"
            >
              View Dashboard <ArrowRight className="w-4 h-4" />
            </Link>
          </motion.div>
        </div>
        
        {/* Status Footer */}
        <div className="mt-8 text-center">
          <div className="inline-flex items-center gap-2 px-4 py-2 bg-green-500/10 border border-green-500/30 rounded-full">
            <div className="w-2 h-2 rounded-full bg-green-400 animate-pulse" />
            <span className="text-green-400 text-sm">All autonomous systems operational</span>
          </div>
        </div>
      </div>
    </div>
  );
}
