'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import Link from 'next/link';
import {
  Building2, Users, Wallet, Package, FileText, TrendingUp,
  ChevronRight, ArrowUpRight, ArrowDownRight, Minus, ExternalLink,
  Shield, Brain, Settings, Eye, Newspaper, BarChart3, Wand2, Sparkles,
  CheckSquare, FolderKanban, Receipt, ArrowLeftRight, Factory,
  BadgeCheck, LifeBuoy, ShoppingCart, Truck, Scale, LucideIcon, HelpCircle
} from 'lucide-react';

/* ── Icon map matching registry icon strings to Lucide components ── */
const ICON_MAP: Record<string, LucideIcon> = {
  Wallet, Users, Package, FileText, TrendingUp, Shield, Brain,
  Settings, Eye, Newspaper, BarChart3, Wand2, Sparkles,
  CheckSquare, FolderKanban, Receipt, ArrowLeftRight, Factory,
  Building2, BadgeCheck, LifeBuoy, ShoppingCart, Truck, Scale,
};

interface ModuleFromAPI {
  moduleId: string;
  name: string;
  description: string | null;
  category: string;
  icon: string | null;
  isEnabled: boolean;
  isCore: boolean;
  sortOrder: number;
  apiRoutes?: string[];
  uiRoutes?: string[];
}

interface ModuleData {
  finance?: { totalAssets?: number; netIncome?: number };
  hr?: { totalEmployees?: number };
  inventory?: { totalProducts?: number; lowStockCount?: number };
  documents?: { totalDocuments?: number; totalContracts?: number };
}

export function OperationsPanel({ compact = false }: { compact?: boolean }) {
  const [enabledModules, setEnabledModules] = useState<ModuleFromAPI[]>([]);
  const [data, setData] = useState<ModuleData>({});
  const [loading, setLoading] = useState(true);

  /* Fetch the list of all modules and filter to enabled ones (non-core) */
  useEffect(() => {
    async function fetchModules() {
      try {
        const res = await fetch('/api/modules');
        const json = await res.json();
        if (json.modules) {
          const active = (json.modules as ModuleFromAPI[])
            .filter(m => m.isEnabled && !m.isCore)
            .sort((a, b) => a.sortOrder - b.sortOrder);
          setEnabledModules(active);
        }
      } catch (err) {
        console.error('Failed to fetch modules for operations panel:', err);
      } finally {
        setLoading(false);
      }
    }
    fetchModules();
  }, []);

  /* Fetch summary metrics for the original 4 ERP data endpoints */
  useEffect(() => {
    async function fetchData() {
      try {
        const [finance, hr, inventory, documents] = await Promise.all([
          fetch('/api/erp/finance').then(r => r.json()).catch(() => ({})),
          fetch('/api/erp/hr').then(r => r.json()).catch(() => ({})),
          fetch('/api/erp/inventory').then(r => r.json()).catch(() => ({})),
          fetch('/api/erp/documents').then(r => r.json()).catch(() => ({})),
        ]);
        setData({
          finance: finance.summary,
          hr: hr.summary,
          inventory: inventory.summary,
          documents: documents.summary,
        });
      } catch (error) {
        console.error('Failed to fetch module data:', error);
      }
    }
    fetchData();
  }, []);

  const formatCurrency = (value: number) => {
    if (value >= 1000000) return `$${(value / 1000000).toFixed(1)}M`;
    if (value >= 1000) return `$${(value / 1000).toFixed(1)}K`;
    return `$${value.toFixed(0)}`;
  };

  /* Build metric + trend for modules that have ERP data endpoints */
  const getMetric = (moduleId: string): { value: string; trend: 'up' | 'down' | 'stable' } | undefined => {
    switch (moduleId) {
      case 'finance':
        return {
          value: data.finance?.totalAssets ? formatCurrency(data.finance.totalAssets) : '$0',
          trend: (data.finance?.netIncome || 0) >= 0 ? 'up' : 'down',
        };
      case 'hr':
        return { value: `${data.hr?.totalEmployees || 0}`, trend: 'stable' };
      case 'inventory':
        return {
          value: `${data.inventory?.totalProducts || 0}`,
          trend: (data.inventory?.lowStockCount || 0) > 0 ? 'down' : 'stable',
        };
      case 'documents':
        return {
          value: `${(data.documents?.totalDocuments || 0) + (data.documents?.totalContracts || 0)}`,
          trend: 'up',
        };
      default:
        return undefined;
    }
  };

  /* Resolve the best href for each module */
  const getHref = (mod: ModuleFromAPI): string => {
    if (mod.uiRoutes && mod.uiRoutes.length > 0) return mod.uiRoutes[0];
    return '/ghost-control/operations';
  };

  const trendIcons = {
    up: <ArrowUpRight className="w-3 h-3 text-green-400" />,
    down: <ArrowDownRight className="w-3 h-3 text-amber-400" />,
    stable: <Minus className="w-3 h-3 text-gray-400" />,
  };

  const statusColors = {
    active: 'bg-green-500/10 text-green-400 border-green-500/30',
    learning: 'bg-brand-deep/10 text-brand border-brand-deep/30',
    coming: 'bg-gray-500/10 text-gray-400 border-gray-500/30',
  };

  return (
    <div className="glass-card p-6 border border-brand-deep/20 h-full">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-3">
          <Building2 className="w-6 h-6 text-brand" />
          <h2 className="text-xl font-bold text-white">Operations</h2>
        </div>
        <Link
          href="/ghost-control/operations"
          className="flex items-center gap-1 px-2 py-1 bg-brand-deep/10 text-brand text-xs rounded-full hover:bg-brand-deep/20 transition-colors"
        >
          <span>ERP Modules</span>
          <ExternalLink className="w-3 h-3" />
        </Link>
      </div>

      {loading ? (
        <div className="flex items-center justify-center h-24 text-gray-500 text-sm">
          Loading modules…
        </div>
      ) : enabledModules.length === 0 ? (
        <div className="flex flex-col items-center justify-center h-24 text-gray-500 text-sm gap-1">
          <Settings className="w-5 h-5 opacity-50" />
          <span>No modules active — enable them in Configuration.</span>
        </div>
      ) : (
        <div className={`space-y-3 ${compact ? 'max-h-64 overflow-y-auto' : 'max-h-[420px] overflow-y-auto scrollbar-hide'}`}>
          {enabledModules.map((mod) => {
            const IconComp = ICON_MAP[mod.icon || ''] || HelpCircle;
            const metric = getMetric(mod.moduleId);
            return (
              <Link key={mod.moduleId} href={getHref(mod)}>
                <motion.div
                  whileHover={{ scale: 1.02 }}
                  className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/10 hover:border-brand-deep/30 transition-colors cursor-pointer group"
                >
                  <div className="flex items-center gap-3">
                    <div className="text-brand">
                      <IconComp className="w-5 h-5" />
                    </div>
                    <div>
                      <div className="flex items-center gap-2">
                        <h3 className="font-medium text-white">{mod.name}</h3>
                        <span className={`px-1.5 py-0.5 text-[10px] rounded border ${statusColors.active}`}>
                          Active
                        </span>
                      </div>
                      {!compact && mod.description && (
                        <p className="text-gray-500 text-xs line-clamp-1">{mod.description}</p>
                      )}
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    {metric && (
                      <div className="text-right">
                        <div className="flex items-center gap-1">
                          <span className="text-white font-semibold">{metric.value}</span>
                          {trendIcons[metric.trend]}
                        </div>
                      </div>
                    )}
                    <ChevronRight className="w-4 h-4 text-gray-500 group-hover:text-brand transition-colors" />
                  </div>
                </motion.div>
              </Link>
            );
          })}
        </div>
      )}

      {!compact && (
        <div className="mt-4 pt-4 border-t border-white/10">
          <Link
            href="/ghost-control/operations"
            className="flex items-center justify-center gap-2 text-brand text-sm hover:text-brand-light transition-colors"
          >
            <span>Open Full Operations Dashboard</span>
            <ChevronRight className="w-4 h-4" />
          </Link>
        </div>
      )}
    </div>
  );
}