'use client';

import { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import Link from 'next/link';
import {
  Grid3X3, PlusCircle, ExternalLink, Cog, Package,
  Calendar, DollarSign, Users, FileText, Zap, Clock
} from 'lucide-react';
import { VOCAB } from '@/lib/white-label/constants';

interface MicroApp {
  id: string;
  name: string;
  description: string;
  icon: React.ReactNode;
  status: 'active' | 'building' | 'draft';
  createdAt: string;
  usageCount: number;
  color: string;
}

const mockApps: MicroApp[] = [
  {
    id: 'k12-pos',
    name: 'K-12 POS System',
    description: 'Point-of-sale for school lunch programs',
    icon: <DollarSign className="w-5 h-5" />,
    status: 'building',
    createdAt: 'Today',
    usageCount: 0,
    color: 'green',
  },
  {
    id: 'expense-tracker',
    name: 'Expense Tracker',
    description: 'Quick expense logging and reporting',
    icon: <FileText className="w-5 h-5" />,
    status: 'draft',
    createdAt: 'Coming soon',
    usageCount: 0,
    color: 'cyan',
  },
  {
    id: 'meeting-rooms',
    name: 'Meeting Rooms',
    description: 'Room booking and availability',
    icon: <Calendar className="w-5 h-5" />,
    status: 'draft',
    createdAt: 'Coming soon',
    usageCount: 0,
    color: 'purple',
  },
];

export function MicroAppsPanel() {
  const [apps, setApps] = useState<MicroApp[]>(mockApps);
  const [projects, setProjects] = useState<any[]>([]);

  useEffect(() => {
    // Fetch ${VOCAB.factory} projects as potential micro-apps
    fetchProjects();
  }, []);

  const fetchProjects = async () => {
    try {
      const res = await fetch('/api/dark-factory/projects');
      if (res.ok) {
        const data = await res.json();
        setProjects(data.projects || []);
      }
    } catch (error) {
      console.error('Failed to fetch projects:', error);
    }
  };

  const statusColors = {
    active: 'bg-green-500/20 text-green-400 border-green-500/30',
    building: 'bg-amber-500/20 text-amber-400 border-amber-500/30',
    draft: 'bg-gray-500/20 text-gray-400 border-gray-500/30',
  };

  const colorClasses: Record<string, string> = {
    green: 'from-green-500/20 to-green-500/5 border-green-500/30 hover:border-green-500/50',
    cyan: 'from-brand-deep/20 to-brand-deep/5 border-brand-deep/30 hover:border-brand-deep/50',
    purple: 'from-brand-secondary/20 to-brand-secondary/5 border-brand-secondary/30 hover:border-brand-secondary/50',
    amber: 'from-amber-500/20 to-amber-500/5 border-amber-500/30 hover:border-amber-500/50',
  };

  const iconColors: Record<string, string> = {
    green: 'text-green-400 bg-green-500/20',
    cyan: 'text-brand bg-brand-deep/20',
    purple: 'text-brand-secondary-light bg-brand-secondary/20',
    amber: 'text-amber-400 bg-amber-500/20',
  };

  return (
    <div className="glass-card p-6 border border-brand-deep/20">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-3">
          <Grid3X3 className="w-6 h-6 text-brand" />
          <div>
            <h2 className="text-xl font-bold text-white">Micro-Apps</h2>
            <p className="text-gray-500 text-sm">Standalone tools built by the {VOCAB.factory}</p>
          </div>
        </div>
        <Link
          href="/ghost-control/dark-factory"
          className="flex items-center gap-2 px-3 py-2 bg-brand-deep/20 text-brand rounded-lg hover:bg-brand-deep/30 transition-colors border border-brand-deep/30"
        >
          <PlusCircle className="w-4 h-4" />
          <span>Create New</span>
        </Link>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        {/* Existing Apps */}
        {apps.map((app) => (
          <motion.div
            key={app.id}
            whileHover={{ scale: 1.02, y: -2 }}
            className={`p-4 rounded-xl bg-gradient-to-br border cursor-pointer transition-all ${colorClasses[app.color]}`}
          >
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center mb-3 ${iconColors[app.color]}`}>
              {app.icon}
            </div>
            <h3 className="font-semibold text-white mb-1">{app.name}</h3>
            <p className="text-gray-500 text-xs mb-3 line-clamp-2">{app.description}</p>
            <div className="flex items-center justify-between">
              <span className={`px-2 py-0.5 text-[10px] rounded border ${statusColors[app.status]}`}>
                {app.status === 'building' ? 'Building...' : app.status === 'active' ? 'Active' : 'Draft'}
              </span>
              {app.status === 'active' && (
                <button className="p-1 text-gray-400 hover:text-white transition-colors">
                  <ExternalLink className="w-3 h-3" />
                </button>
              )}
            </div>
          </motion.div>
        ))}

        {/* Create New App Card */}
        <Link href="/ghost-control/dark-factory">
          <motion.div
            whileHover={{ scale: 1.02, y: -2 }}
            className="p-4 rounded-xl border-2 border-dashed border-white/20 hover:border-brand-deep/50 cursor-pointer transition-all flex flex-col items-center justify-center min-h-[160px] bg-white/5 hover:bg-brand-deep/5"
          >
            <PlusCircle className="w-10 h-10 text-gray-500 mb-2" />
            <span className="text-gray-400 font-medium">New App</span>
            <span className="text-gray-600 text-xs">via {VOCAB.factory}</span>
          </motion.div>
        </Link>
      </div>

      {/* ${VOCAB.factory} Projects as Potential Apps */}
      {projects.length > 0 && (
        <div className="mt-6 pt-6 border-t border-white/10">
          <h3 className="text-sm font-semibold text-gray-400 mb-3">From {VOCAB.factory} Projects</h3>
          <div className="flex flex-wrap gap-2">
            {projects.slice(0, 5).map((project) => (
              <Link
                key={project.id}
                href={`/ghost-control/dark-factory?project=${project.id}`}
                className="flex items-center gap-2 px-3 py-1.5 bg-white/5 rounded-lg text-sm text-gray-300 hover:bg-white/10 transition-colors border border-white/10"
              >
                <Package className="w-3 h-3 text-brand-secondary-light" />
                <span>{project.name}</span>
              </Link>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
