'use client';

import { ATAButton } from '@/components/agent-hierarchy/ata-flyout';
import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import {
  Wallet, TrendingUp, TrendingDown, CreditCard, Receipt,
  PiggyBank, DollarSign, ArrowUpRight, ArrowDownRight, Plus,
  FileText, AlertCircle, CheckCircle, Loader2
} from 'lucide-react';
import { ERPModal } from '@/components/erp/erp-modal';

interface FinanceData {
  summary: {
    totalAssets: number;
    totalLiabilities: number;
    totalRevenue: number;
    totalExpenses: number;
    netIncome: number;
    netWorth: number;
    accountCount: number;
    pendingInvoicesCount: number;
    overdueInvoicesAmount: number;
    activeBudgets: number;
    budgetUtilization: number;
  };
  recentTransactions: Array<{
    id: string;
    type: string;
    description: string;
    amount: number;
    date: string;
    status: string;
    account: { name: string; code: string };
  }>;
  recentInvoices: Array<{
    id: string;
    invoiceNumber: string;
    total: number;
    status: string;
    dueDate: string;
  }>;
}

interface Account {
  id: string;
  name: string;
  code: string;
  type: string;
}

export default function FinanceDashboard() {
  const [data, setData] = useState<FinanceData | null>(null);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [accounts, setAccounts] = useState<Account[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [formData, setFormData] = useState({
    accountId: '',
    type: 'expense',
    description: '',
    amount: '',
    reference: '',
  });

  const fetchData = () => {
    setLoading(true);
    fetch('/api/erp/finance')
      .then((r) => r.json())
      .then((d) => setData(d))
      .finally(() => setLoading(false));
  };

  useEffect(() => {
    fetchData();
    // Fetch accounts for the dropdown
    fetch('/api/erp/finance?type=accounts')
      .then(r => r.json())
      .then(d => setAccounts(d.accounts || []));
  }, []);

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

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.accountId || !formData.description || !formData.amount) return;
    
    setSubmitting(true);
    try {
      const amount = formData.type === 'expense' || formData.type === 'payment' 
        ? -Math.abs(parseFloat(formData.amount))
        : Math.abs(parseFloat(formData.amount));
        
      const res = await fetch('/api/erp/finance', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          entity: 'transaction',
          data: {
            accountId: formData.accountId,
            type: formData.type,
            description: formData.description,
            amount,
            reference: formData.reference || null,
            date: new Date().toISOString(),
            status: 'completed',
          },
        }),
      });
      
      if (res.ok) {
        setShowModal(false);
        setFormData({ accountId: '', type: 'expense', description: '', amount: '', reference: '' });
        fetchData();
      }
    } catch (error) {
      console.error('Failed to create transaction:', error);
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="space-y-6">
        <div className="h-8 w-48 bg-white/10 rounded animate-pulse" />
        <div className="grid grid-cols-4 gap-4">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="h-32 bg-white/5 rounded-lg animate-pulse" />
          ))}
        </div>
      </div>
    );
  }

  const summary = data?.summary || {} as FinanceData['summary'];

  const kpiCards = [
    {
      label: 'Total Assets',
      value: formatCurrency(summary.totalAssets),
      icon: <DollarSign className="w-5 h-5" />,
      color: 'cyan',
      trend: 'up',
    },
    {
      label: 'Net Income',
      value: formatCurrency(summary.netIncome),
      icon: <TrendingUp className="w-5 h-5" />,
      color: summary.netIncome >= 0 ? 'green' : 'red',
      trend: summary.netIncome >= 0 ? 'up' : 'down',
    },
    {
      label: 'Liabilities',
      value: formatCurrency(summary.totalLiabilities),
      icon: <CreditCard className="w-5 h-5" />,
      color: 'amber',
    },
    {
      label: 'Net Worth',
      value: formatCurrency(summary.netWorth),
      icon: <Wallet className="w-5 h-5" />,
      color: 'purple',
    },
  ];

  const colorClasses: Record<string, { bg: string; text: string; border: string }> = {
    cyan: { bg: 'bg-brand-deep/10', text: 'text-brand', border: 'border-brand-deep/30' },
    green: { bg: 'bg-green-500/10', text: 'text-green-400', border: 'border-green-500/30' },
    red: { bg: 'bg-red-500/10', text: 'text-red-400', border: 'border-red-500/30' },
    amber: { bg: 'bg-amber-500/10', text: 'text-amber-400', border: 'border-amber-500/30' },
    purple: { bg: 'bg-brand-secondary/10', text: 'text-brand-secondary-light', border: 'border-brand-secondary/30' },
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Finance Dashboard</h1>
          <p className="text-gray-400 text-sm">Cash flow, accounts, and budgeting</p>
        </div>
        <div className="flex items-center gap-3">
          <ATAButton agentId="agent-finance" variant="compact" />
          <button 
            onClick={() => setShowModal(true)}
            className="flex items-center gap-2 px-4 py-2 bg-brand-deep/20 text-brand rounded-lg hover:bg-brand-deep/30 transition-colors border border-brand-deep/30"
          >
            <Plus className="w-4 h-4" />
            <span>New Transaction</span>
          </button>
        </div>
      </div>

      {/* KPI Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        {kpiCards.map((card, idx) => (
          <motion.div
            key={card.label}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: idx * 0.1 }}
            className={`glass-card p-4 border ${colorClasses[card.color].border}`}
          >
            <div className="flex items-center justify-between mb-2">
              <span className="text-gray-400 text-sm">{card.label}</span>
              <div className={`p-1.5 rounded ${colorClasses[card.color].bg}`}>
                <span className={colorClasses[card.color].text}>{card.icon}</span>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-2xl font-bold text-white">{card.value}</span>
              {card.trend === 'up' && <ArrowUpRight className="w-4 h-4 text-green-400" />}
              {card.trend === 'down' && <ArrowDownRight className="w-4 h-4 text-red-400" />}
            </div>
          </motion.div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Transactions */}
        <div className="glass-card p-6 border border-white/10">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-white flex items-center gap-2">
              <Receipt className="w-5 h-5 text-brand" />
              Recent Transactions
            </h2>
          </div>
          {data?.recentTransactions?.length ? (
            <div className="space-y-3">
              {data.recentTransactions.filter(tx => tx && tx.id).slice(0, 5).map((tx) => (
                <div key={tx.id} className="flex items-center justify-between p-3 bg-white/5 rounded-lg">
                  <div>
                    <p className="text-white text-sm font-medium">{tx.description || 'Transaction'}</p>
                    <p className="text-gray-500 text-xs">{tx.account?.name || 'Unknown Account'}</p>
                  </div>
                  <div className="text-right">
                    <p className={`font-semibold ${(tx.amount ?? 0) >= 0 ? 'text-green-400' : 'text-red-400'}`}>
                      {(tx.amount ?? 0) >= 0 ? '+' : ''}{formatCurrency(tx.amount ?? 0)}
                    </p>
                    <p className="text-gray-500 text-xs">{tx.date ? new Date(tx.date).toLocaleDateString() : 'N/A'}</p>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              <Receipt className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p>No transactions yet</p>
            </div>
          )}
        </div>

        {/* Budget Overview */}
        <div className="glass-card p-6 border border-white/10">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold text-white flex items-center gap-2">
              <PiggyBank className="w-5 h-5 text-brand-secondary-light" />
              Budget Status
            </h2>
          </div>
          <div className="space-y-4">
            <div className="p-4 bg-white/5 rounded-lg">
              <div className="flex items-center justify-between mb-2">
                <span className="text-gray-400">Active Budgets</span>
                <span className="text-white font-semibold">{summary.activeBudgets || 0}</span>
              </div>
              <div className="flex items-center justify-between mb-2">
                <span className="text-gray-400">Overall Utilization</span>
                <span className="text-brand font-semibold">{(summary.budgetUtilization || 0).toFixed(1)}%</span>
              </div>
              <div className="w-full bg-white/10 rounded-full h-2 mt-3">
                <div
                  className="bg-gradient-to-r from-brand-deep to-brand-secondary h-2 rounded-full transition-all"
                  style={{ width: `${Math.min(summary.budgetUtilization || 0, 100)}%` }}
                />
              </div>
            </div>

            {/* Invoice Alerts */}
            <div className="space-y-2">
              <h3 className="text-sm font-medium text-gray-400">Alerts</h3>
              {summary.overdueInvoicesAmount > 0 ? (
                <div className="flex items-center gap-3 p-3 bg-amber-500/10 rounded-lg border border-amber-500/30">
                  <AlertCircle className="w-4 h-4 text-amber-400" />
                  <span className="text-amber-400 text-sm">
                    {formatCurrency(summary.overdueInvoicesAmount)} in overdue invoices
                  </span>
                </div>
              ) : (
                <div className="flex items-center gap-3 p-3 bg-green-500/10 rounded-lg border border-green-500/30">
                  <CheckCircle className="w-4 h-4 text-green-400" />
                  <span className="text-green-400 text-sm">All invoices up to date</span>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Quick Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div className="p-4 bg-white/5 rounded-lg border border-white/10">
          <p className="text-gray-500 text-xs">Revenue</p>
          <p className="text-green-400 font-semibold">{formatCurrency(summary.totalRevenue)}</p>
        </div>
        <div className="p-4 bg-white/5 rounded-lg border border-white/10">
          <p className="text-gray-500 text-xs">Expenses</p>
          <p className="text-red-400 font-semibold">{formatCurrency(summary.totalExpenses)}</p>
        </div>
        <div className="p-4 bg-white/5 rounded-lg border border-white/10">
          <p className="text-gray-500 text-xs">Accounts</p>
          <p className="text-white font-semibold">{summary.accountCount || 0}</p>
        </div>
        <div className="p-4 bg-white/5 rounded-lg border border-white/10">
          <p className="text-gray-500 text-xs">Pending Invoices</p>
          <p className="text-amber-400 font-semibold">{summary.pendingInvoicesCount || 0}</p>
        </div>
      </div>

      {/* New Transaction Modal */}
      <ERPModal isOpen={showModal} onClose={() => setShowModal(false)} title="New Transaction">
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm text-gray-400 mb-1">Account *</label>
            <select
              value={formData.accountId}
              onChange={(e) => setFormData({ ...formData, accountId: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep/50 focus:outline-none"
              required
            >
              <option value="" className="bg-brand-bg">Select account...</option>
              {accounts.map((acc) => (
                <option key={acc.id} value={acc.id} className="bg-brand-bg">
                  {acc.code} - {acc.name}
                </option>
              ))}
            </select>
          </div>
          
          <div>
            <label className="block text-sm text-gray-400 mb-1">Type *</label>
            <select
              value={formData.type}
              onChange={(e) => setFormData({ ...formData, type: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep/50 focus:outline-none"
            >
              <option value="expense" className="bg-brand-bg">Expense</option>
              <option value="income" className="bg-brand-bg">Income</option>
              <option value="payment" className="bg-brand-bg">Payment</option>
              <option value="receipt" className="bg-brand-bg">Receipt</option>
              <option value="transfer" className="bg-brand-bg">Transfer</option>
            </select>
          </div>
          
          <div>
            <label className="block text-sm text-gray-400 mb-1">Description *</label>
            <input
              type="text"
              value={formData.description}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep/50 focus:outline-none"
              placeholder="e.g., Office supplies purchase"
              required
            />
          </div>
          
          <div>
            <label className="block text-sm text-gray-400 mb-1">Amount *</label>
            <input
              type="number"
              step="0.01"
              min="0"
              value={formData.amount}
              onChange={(e) => setFormData({ ...formData, amount: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep/50 focus:outline-none"
              placeholder="0.00"
              required
            />
          </div>
          
          <div>
            <label className="block text-sm text-gray-400 mb-1">Reference (optional)</label>
            <input
              type="text"
              value={formData.reference}
              onChange={(e) => setFormData({ ...formData, reference: e.target.value })}
              className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white focus:border-brand-deep/50 focus:outline-none"
              placeholder="e.g., INV-001"
            />
          </div>
          
          <div className="flex gap-3 pt-4">
            <button
              type="button"
              onClick={() => setShowModal(false)}
              className="flex-1 px-4 py-2 bg-white/5 text-gray-400 rounded-lg hover:bg-white/10 transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting}
              className="flex-1 px-4 py-2 bg-brand-deep/20 text-brand rounded-lg hover:bg-brand-deep/30 transition-colors border border-brand-deep/30 disabled:opacity-50 flex items-center justify-center gap-2"
            >
              {submitting && <Loader2 className="w-4 h-4 animate-spin" />}
              {submitting ? 'Creating...' : 'Create Transaction'}
            </button>
          </div>
        </form>
      </ERPModal>
    </div>
  );
}
