'use client';

import { useState } from 'react';
import { motion } from 'framer-motion';
import {
  Settings, Shield, Brain, Wallet, Users, Package, TrendingUp, FileText,
  CheckSquare, FolderKanban, Receipt, ArrowLeftRight, Factory, Building2,
  BadgeCheck, LifeBuoy, ShoppingCart, Truck, Scale, Eye, Newspaper,
  BarChart3, Wand2, Sparkles, Lock, AlertTriangle, ChevronDown, ChevronUp,
  Zap, Power, PowerOff
} from 'lucide-react';

const ICON_MAP: Record<string, React.ElementType> = {
  Settings, Shield, Brain, Wallet, Users, Package, TrendingUp, FileText,
  CheckSquare, FolderKanban, Receipt, ArrowLeftRight, Factory, Building2,
  BadgeCheck, LifeBuoy, ShoppingCart, Truck, Scale, Eye, Newspaper,
  BarChart3, Wand2, Sparkles,
};

const TIER_COLORS: Record<string, string> = {
  starter: 'text-green-400 bg-green-400/10 border-green-400/30',
  professional: 'text-blue-400 bg-blue-400/10 border-blue-400/30',
  enterprise: 'text-brand-secondary-light bg-brand-secondary-light/10 border-brand-secondary-light/30',
};

const CATEGORY_COLORS: Record<string, string> = {
  core: 'border-l-cyan-400',
  operations: 'border-l-blue-400',
  intelligence: 'border-l-purple-400',
  addon: 'border-l-amber-400',
};

interface ModuleCardProps {
  module: {
    moduleId: string;
    name: string;
    description: string | null;
    category: string;
    icon: string | null;
    isEnabled: boolean;
    isCore: boolean;
    features: string[];
    tier: string;
    agentId: string | null;
    dependencies: unknown;
  };
  onToggle: (moduleId: string, action: 'enable' | 'disable') => Promise<void>;
  isToggling: boolean;
}

export function ModuleCard({ module, onToggle, isToggling }: ModuleCardProps) {
  const [expanded, setExpanded] = useState(false);
  const IconComponent = ICON_MAP[module.icon || 'Settings'] || Settings;
  const deps = Array.isArray(module.dependencies) ? module.dependencies as string[] : [];

  return (
    <motion.div
      layout
      className={`relative rounded-xl border-l-4 ${
        CATEGORY_COLORS[module.category] || 'border-l-gray-400'
      } bg-slate-800/80 border border-slate-700/50 overflow-hidden transition-all duration-200 ${
        module.isEnabled ? 'ring-1 ring-brand-deep/20' : 'opacity-75'
      }`}
    >
      <div className="p-4">
        <div className="flex items-start justify-between gap-3">
          <div className="flex items-start gap-3 flex-1 min-w-0">
            <div className={`p-2 rounded-lg ${
              module.isEnabled ? 'bg-brand-deep/10 text-brand' : 'bg-slate-700/50 text-slate-500'
            }`}>
              <IconComponent className="w-5 h-5" />
            </div>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 flex-wrap">
                <h4 className="text-sm font-semibold text-white truncate">{module.name}</h4>
                {module.isCore && (
                  <span className="flex items-center gap-1 text-[10px] font-medium text-brand bg-brand/10 px-1.5 py-0.5 rounded border border-brand/30">
                    <Lock className="w-2.5 h-2.5" /> CORE
                  </span>
                )}
                <span className={`text-[10px] font-medium px-1.5 py-0.5 rounded border ${TIER_COLORS[module.tier] || TIER_COLORS.starter}`}>
                  {module.tier}
                </span>
              </div>
              <p className="text-xs text-gray-400 mt-1 line-clamp-2">{module.description}</p>
            </div>
          </div>

          {/* Toggle */}
          <div className="flex items-center gap-2 shrink-0">
            {module.isCore ? (
              <div className="flex items-center gap-1 text-[10px] text-brand">
                <Zap className="w-3 h-3" /> Always On
              </div>
            ) : (
              <button
                onClick={() => onToggle(module.moduleId, module.isEnabled ? 'disable' : 'enable')}
                disabled={isToggling}
                className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-200 focus:outline-none ${
                  isToggling ? 'opacity-50 cursor-wait' : 'cursor-pointer'
                } ${module.isEnabled ? 'bg-brand-deep' : 'bg-slate-600'}`}
              >
                <span
                  className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform duration-200 ${
                    module.isEnabled ? 'translate-x-6' : 'translate-x-1'
                  }`}
                />
              </button>
            )}
          </div>
        </div>

        {/* Agent badge */}
        {module.agentId && (
          <div className="mt-2 flex items-center gap-1.5">
            <Brain className="w-3 h-3 text-brand-secondary-light" />
            <span className="text-[10px] text-brand-secondary-light">Powered by {module.agentId.replace('agent-', 'Agent ').replace(/^\w/, c => c.toUpperCase())}</span>
          </div>
        )}

        {/* Expand toggle */}
        <button
          onClick={() => setExpanded(!expanded)}
          className="mt-2 flex items-center gap-1 text-[10px] text-gray-500 hover:text-gray-300 transition-colors"
        >
          {expanded ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
          {expanded ? 'Less' : 'Details'}
        </button>

        {/* Expanded details */}
        {expanded && (
          <motion.div
            initial={{ opacity: 0, height: 0 }}
            animate={{ opacity: 1, height: 'auto' }}
            className="mt-3 pt-3 border-t border-slate-700/50 space-y-2"
          >
            {module.features.length > 0 && (
              <div>
                <span className="text-[10px] font-medium text-gray-400 uppercase tracking-wider">Features</span>
                <div className="flex flex-wrap gap-1 mt-1">
                  {module.features.map(f => (
                    <span key={f} className="text-[10px] px-1.5 py-0.5 bg-slate-700/50 text-gray-300 rounded">{f}</span>
                  ))}
                </div>
              </div>
            )}
            {deps.length > 0 && (
              <div>
                <span className="text-[10px] font-medium text-gray-400 uppercase tracking-wider">Requires</span>
                <div className="flex flex-wrap gap-1 mt-1">
                  {deps.map((d: string) => (
                    <span key={d} className="text-[10px] px-1.5 py-0.5 bg-amber-500/10 text-amber-300 border border-amber-500/20 rounded">{d}</span>
                  ))}
                </div>
              </div>
            )}
          </motion.div>
        )}
      </div>

      {/* Status indicator bar */}
      <div className={`h-0.5 ${module.isEnabled ? 'bg-gradient-to-r from-brand-deep to-brand-secondary' : 'bg-slate-700'}`} />
    </motion.div>
  );
}
