'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import Link from 'next/link';
import {
  Wallet, Users, Package, FileText, TrendingUp, TrendingDown,
  AlertTriangle, CheckCircle, Activity, ArrowRight, Brain,
  DollarSign, UserCheck, Boxes, ScrollText
} from 'lucide-react';

interface ModuleSummary {
  finance: {
    totalAssets: number;
    netIncome: number;
    pendingInvoicesCount: number;
    overdueInvoicesAmount: number;
  };
  hr: {
    totalEmployees: number;
    pendingLeaveRequests: number;
    monthlyPayroll: number;
  };
  inventory: {
    totalProducts: number;
    lowStockCount: number;
    stockValue: number;
  };
  documents: {
    totalDocuments: number;
    totalContracts: number;
    expiringContractsCount: number;
  };
}

export default function OperationsOverview() {
  const [data, setData] = useState<ModuleSummary | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      try {
        const [finance, hr, inventory, documents] = await Promise.all([
          fetch('/api/erp/finance').then((r) => r.json()),
          fetch('/api/erp/hr').then((r) => r.json()),
          fetch('/api/erp/inventory').then((r) => r.json()),
          fetch('/api/erp/documents').then((r) => r.json()),
        ]);

        setData({
          finance: finance.summary || {},
          hr: hr.summary || {},
          inventory: inventory.summary || {},
          documents: documents.summary || {},
        });
      } catch (error) {
        console.error('Failed to fetch data:', error);
      } finally {
        setLoading(false);
      }
    }
    fetchData();
  }, []);

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

  const modules = [
    {
      id: 'finance',
      name: 'Finance',
      icon: <Wallet className="w-6 h-6" />,
      color: 'cyan',
      href: '/ghost-control/operations/finance',
      stats: [
        { label: 'Total Assets', value: formatCurrency(data?.finance?.totalAssets || 0), icon: <DollarSign className="w-4 h-4" /> },
        { label: 'Net Income', value: formatCurrency(data?.finance?.netIncome || 0), trend: 'up' },
        { label: 'Pending Invoices', value: data?.finance?.pendingInvoicesCount || 0 },
        { label: 'Overdue Amount', value: formatCurrency(data?.finance?.overdueInvoicesAmount || 0), alert: (data?.finance?.overdueInvoicesAmount || 0) > 0 },
      ],
    },
    {
      id: 'hr',
      name: 'HR & People',
      icon: <Users className="w-6 h-6" />,
      color: 'purple',
      href: '/ghost-control/operations/hr',
      stats: [
        { label: 'Total Employees', value: data?.hr?.totalEmployees || 0, icon: <UserCheck className="w-4 h-4" /> },
        { label: 'Pending Leave', value: data?.hr?.pendingLeaveRequests || 0, alert: (data?.hr?.pendingLeaveRequests || 0) > 0 },
        { label: 'Monthly Payroll', value: formatCurrency(data?.hr?.monthlyPayroll || 0) },
      ],
    },
    {
      id: 'inventory',
      name: 'Inventory',
      icon: <Package className="w-6 h-6" />,
      color: 'green',
      href: '/ghost-control/operations/inventory',
      stats: [
        { label: 'Products', value: data?.inventory?.totalProducts || 0, icon: <Boxes className="w-4 h-4" /> },
        { label: 'Low Stock Alerts', value: data?.inventory?.lowStockCount || 0, alert: (data?.inventory?.lowStockCount || 0) > 0 },
        { label: 'Stock Value', value: formatCurrency(data?.inventory?.stockValue || 0) },
      ],
    },
    {
      id: 'documents',
      name: 'Documents',
      icon: <FileText className="w-6 h-6" />,
      color: 'amber',
      href: '/ghost-control/operations/documents',
      stats: [
        { label: 'Documents', value: data?.documents?.totalDocuments || 0, icon: <ScrollText className="w-4 h-4" /> },
        { label: 'Contracts', value: data?.documents?.totalContracts || 0 },
        { label: 'Expiring Soon', value: data?.documents?.expiringContractsCount || 0, alert: (data?.documents?.expiringContractsCount || 0) > 0 },
      ],
    },
    {
      id: 'order-to-cash',
      name: 'Order-to-Cash',
      icon: <Activity className="w-6 h-6" />,
      color: 'pink',
      href: '/ghost-control/order-to-cash',
      stats: [
        { label: 'Autonomous Rate', value: '100%', icon: <Brain className="w-4 h-4" /> },
        { label: 'Status', value: 'Live', trend: 'up' },
        { label: 'Sniff Checks', value: 0 },
      ],
      featured: true,
    },
  ];

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

  return (
    <div className="space-y-8">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold gradient-text">Operations Overview</h1>
          <p className="text-gray-400 mt-1">Your unified ERP command center</p>
        </div>
        <div className="flex items-center gap-2 px-4 py-2 bg-brand-deep/10 rounded-lg border border-brand-deep/30">
          <Activity className="w-4 h-4 text-brand animate-pulse" />
          <span className="text-brand text-sm">All Systems Operational</span>
        </div>
      </div>

      {/* Module Cards */}
      {loading ? (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {[1, 2, 3, 4].map((i) => (
            <div key={i} className="glass-card p-6 border border-white/10 animate-pulse">
              <div className="h-8 w-32 bg-white/10 rounded mb-4" />
              <div className="space-y-3">
                <div className="h-6 w-full bg-white/5 rounded" />
                <div className="h-6 w-3/4 bg-white/5 rounded" />
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {modules.map((module, idx) => (
            <motion.div
              key={module.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: idx * 0.1 }}
            >
              <Link href={module.href}>
                <div
                  className={`glass-card p-6 border ${colorClasses[module.color].border} hover:${colorClasses[module.color].bg} transition-all duration-300 cursor-pointer group`}
                >
                  <div className="flex items-center justify-between mb-4">
                    <div className="flex items-center gap-3">
                      <div className={`p-2 ${colorClasses[module.color].bg} rounded-lg ${colorClasses[module.color].text}`}>
                        {module.icon}
                      </div>
                      <h2 className="text-xl font-bold text-white">{module.name}</h2>
                    </div>
                    <ArrowRight className="w-5 h-5 text-gray-500 group-hover:text-white group-hover:translate-x-1 transition-all" />
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    {module.stats.map((stat, i) => (
                      <div key={i} className="p-3 bg-white/5 rounded-lg">
                        <div className="flex items-center gap-2 mb-1">
                          {'icon' in stat && stat.icon && <span className={colorClasses[module.color].text}>{stat.icon}</span>}
                          <span className="text-gray-500 text-xs">{stat.label}</span>
                          {'alert' in stat && stat.alert && <AlertTriangle className="w-3 h-3 text-amber-400" />}
                          {'trend' in stat && stat.trend === 'up' && <TrendingUp className="w-3 h-3 text-green-400" />}
                          {'trend' in stat && stat.trend === 'down' && <TrendingDown className="w-3 h-3 text-red-400" />}
                        </div>
                        <p className="text-white font-semibold">{stat.value}</p>
                      </div>
                    ))}
                  </div>
                </div>
              </Link>
            </motion.div>
          ))}
        </div>
      )}

      {/* Ghost Insights */}
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ delay: 0.5 }}
        className="glass-card p-6 border border-brand-deep/20"
      >
        <div className="flex items-center gap-3 mb-4">
          <Brain className="w-6 h-6 text-brand" />
          <h2 className="text-xl font-bold text-white">Ghost Observations</h2>
        </div>
        <div className="space-y-3">
          <div className="flex items-center gap-3 p-3 bg-brand-deep/5 rounded-lg border border-brand-deep/20">
            <CheckCircle className="w-4 h-4 text-brand" />
            <span className="text-gray-300 text-sm">ERP modules initialized and connected</span>
          </div>
          <div className="flex items-center gap-3 p-3 bg-amber-500/5 rounded-lg border border-amber-500/20">
            <AlertTriangle className="w-4 h-4 text-amber-400" />
            <span className="text-gray-300 text-sm">Consider adding sample data to start learning patterns</span>
          </div>
          <div className="flex items-center gap-3 p-3 bg-brand-secondary/5 rounded-lg border border-brand-secondary/20">
            <Activity className="w-4 h-4 text-brand-secondary-light" />
            <span className="text-gray-300 text-sm">Pattern recognition will activate after 100+ transactions</span>
          </div>
        </div>
      </motion.div>
    </div>
  );
}
