'use client';

import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Mail, 
  Users, 
  BarChart3, 
  Database, 
  Zap, 
  Globe, 
  Shield, 
  Bell,
  Settings,
  FileText,
  TrendingUp,
  ArrowLeft,
  Plus,
  Edit,
  Trash2,
  Eye,
  Save,
  Upload,
  Bold,
  Italic,
  List,
  Link as LinkIcon,
  Image as ImageIcon,
  Code,
  Quote,
  ChevronDown,
  ChevronRight,
  Palette,
  Smile
} from 'lucide-react';
import Link from 'next/link';
import ReactMarkdown from 'react-markdown';
import { EmailManager } from './EmailManager';
import { AnalyticsDashboard } from './AnalyticsDashboard';
import ImportExport from './ImportExport';

interface Project {
  id: number;
  title: string;
  description: string;
  content: string;
  tags: string[];
  featured: boolean;
  category: string;
  date: string;
  github?: string;
  live?: string;
  published: boolean;
  imageUrl?: string;
  metaDescription?: string;
  keywords?: string;
  ogImage?: string;
  schema?: Record<string, unknown>;
  difficulty: 'Beginner' | 'Intermediate' | 'Advanced' | 'Expert';
  timeToComplete?: string;
  technologies: string[];
  challenges: string[];
  lessonsLearned: string[];
  futureImprovements: string[];
  demoVideo?: string;
  screenshots: string[];
  colorScheme: string;
  accessibility: boolean;
  performance: {
    lighthouse: number;
    bundleSize: string;
    loadTime: string;
  };
  analytics: {
    views: number;
    likes: number;
    shares: number;
  };
}

const ModernAdminDashboard: React.FC = () => {
  const [activeTab, setActiveTab] = useState<'overview' | 'projects' | 'emails' | 'analytics' | 'settings'>('overview');
  const [projects, setProjects] = useState<Project[]>([]);
  const [selectedProject, setSelectedProject] = useState<Project | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [showProjectEditor, setShowProjectEditor] = useState(false);
  const [isPreview, setIsPreview] = useState(false);
  const [markdownContent, setMarkdownContent] = useState('');
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    content: '',
    tags: '',
    category: '',
    featured: false,
    github: '',
    live: '',
    published: true,
    imageUrl: '',
    difficulty: 'Intermediate' as 'Beginner' | 'Intermediate' | 'Advanced' | 'Expert',
    timeToComplete: '',
    technologies: '',
    challenges: '',
    lessonsLearned: '',
    futureImprovements: '',
    demoVideo: '',
    screenshots: '',
    colorScheme: 'Dark',
    accessibility: true,
    performance: {
      lighthouse: 90,
      bundleSize: '50KB',
      loadTime: '1.5s'
    },
    analytics: {
      views: 0,
      likes: 0,
      shares: 0
    }
  });

  // Mock stats for overview
  const stats = {
    totalProjects: projects.length,
    publishedProjects: projects.filter(p => p.published).length,
    totalViews: projects.reduce((sum, p) => sum + p.analytics.views, 0),
    unreadEmails: 3, // This would come from your email API
    avgPerformance: Math.round(projects.reduce((sum, p) => sum + p.performance.lighthouse, 0) / projects.length) || 90
  };

  useEffect(() => {
    loadProjects();
  }, []);

  const loadProjects = async () => {
    try {
      setIsLoading(true);
      const response = await fetch('/api/projects');
      const data = await response.json();
      setProjects(data.projects || []);
    } catch (error) {
      console.error('Error loading projects:', error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleEdit = (project: Project) => {
    setSelectedProject(project);
    setFormData({
      title: project.title,
      description: project.description,
      content: project.content,
      tags: project.tags.join(', '),
      category: project.category,
      featured: project.featured,
      github: project.github || '',
      live: project.live || '',
      published: project.published,
      imageUrl: project.imageUrl || '',
      difficulty: project.difficulty,
      timeToComplete: project.timeToComplete || '',
      technologies: project.technologies.join(', '),
      challenges: project.challenges.join(', '),
      lessonsLearned: project.lessonsLearned.join(', '),
      futureImprovements: project.futureImprovements.join(', '),
      demoVideo: project.demoVideo || '',
      screenshots: project.screenshots.join(', '),
      colorScheme: project.colorScheme,
      accessibility: project.accessibility,
      performance: project.performance,
      analytics: project.analytics
    });
    setMarkdownContent(project.content);
    setShowProjectEditor(true);
  };

  const handleSave = async () => {
    // Save logic here
    console.log('Saving project...');
    await loadProjects();
    setShowProjectEditor(false);
    setSelectedProject(null);
  };

  const handleDelete = async (projectId: number) => {
    if (confirm('Are you sure you want to delete this project?')) {
      try {
        await fetch(`/api/projects/${projectId}`, { method: 'DELETE' });
        await loadProjects();
      } catch (error) {
        console.error('Error deleting project:', error);
      }
    }
  };

  const resetForm = () => {
    setSelectedProject(null);
    setFormData({
      title: '',
      description: '',
      content: '',
      tags: '',
      category: '',
      featured: false,
      github: '',
      live: '',
      published: true,
      imageUrl: '',
      difficulty: 'Intermediate' as 'Beginner' | 'Intermediate' | 'Advanced' | 'Expert',
      timeToComplete: '',
      technologies: '',
      challenges: '',
      lessonsLearned: '',
      futureImprovements: '',
      demoVideo: '',
      screenshots: '',
      colorScheme: 'Dark',
      accessibility: true,
      performance: {
        lighthouse: 90,
        bundleSize: '50KB',
        loadTime: '1.5s'
      },
      analytics: {
        views: 0,
        likes: 0,
        shares: 0
      }
    });
    setMarkdownContent('');
    setShowProjectEditor(false);
  };

  const tabs = [
    { id: 'overview', label: 'Overview', icon: BarChart3, color: 'blue' },
    { id: 'projects', label: 'Projects', icon: FileText, color: 'green' },
    { id: 'emails', label: 'Emails', icon: Mail, color: 'purple' },
    { id: 'analytics', label: 'Analytics', icon: TrendingUp, color: 'orange' },
    { id: 'settings', label: 'Settings', icon: Settings, color: 'gray' }
  ];

  const categories = [
    "Web Development", "Full-Stack", "Web Application", "Mobile App", 
    "Desktop App", "API Development", "Database Design", "DevOps", 
    "UI/UX Design", "Game Development", "Machine Learning", "Data Science", 
    "Blockchain", "IoT", "Cybersecurity"
  ];

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900">
      {/* Header */}
      <div className="bg-white/5 backdrop-blur-md border-b border-white/10 sticky top-0 z-50">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            <div className="flex items-center space-x-4">
              <Link
                href="/"
                className="flex items-center space-x-2 text-white/80 hover:text-white transition-colors"
              >
                <ArrowLeft size={20} />
                <span>Back to Portfolio</span>
              </Link>
              <div className="h-6 w-px bg-white/20" />
              <h1 className="text-xl font-bold text-white">Admin Dashboard</h1>
            </div>
            
            <div className="flex items-center space-x-4">
              <div className="flex items-center space-x-2 text-sm text-white/60">
                <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
                <span>Live</span>
              </div>
              <div className="text-sm text-white/60 font-mono">
                dk<span className="text-red-500">0</span>.dev
              </div>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
          
          {/* Sidebar */}
          <div className="lg:col-span-1">
            <div className="bg-white/5 backdrop-blur-md rounded-2xl border border-white/10 p-6">
              <nav className="space-y-2">
                {tabs.map((tab) => {
                  const Icon = tab.icon;
                  return (
                    <button
                      key={tab.id}
                      onClick={() => setActiveTab(tab.id as any)}
                      className={`w-full flex items-center space-x-3 px-4 py-3 rounded-xl transition-all duration-200 ${
                        activeTab === tab.id
                          ? `bg-${tab.color}-500/20 text-${tab.color}-400 border border-${tab.color}-500/30`
                          : 'text-white/60 hover:text-white hover:bg-white/5'
                      }`}
                    >
                      <Icon size={20} />
                      <span className="font-medium">{tab.label}</span>
                      {tab.id === 'emails' && stats.unreadEmails > 0 && (
                        <span className="ml-auto bg-red-500 text-white text-xs px-2 py-1 rounded-full">
                          {stats.unreadEmails}
                        </span>
                      )}
                    </button>
                  );
                })}
              </nav>
            </div>
          </div>

          {/* Main Content */}
          <div className="lg:col-span-3">
            <AnimatePresence mode="wait">
              {activeTab === 'overview' && (
                <motion.div
                  key="overview"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className="space-y-6"
                >
                  {/* Stats Grid */}
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                    <div className="bg-white/5 backdrop-blur-md rounded-2xl border border-white/10 p-6">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-white/60 text-sm">Total Projects</p>
                          <p className="text-2xl font-bold text-white">{stats.totalProjects}</p>
                        </div>
                        <div className="w-12 h-12 bg-blue-500/20 rounded-xl flex items-center justify-center">
                          <FileText className="w-6 h-6 text-blue-400" />
                        </div>
                      </div>
                    </div>

                    <div className="bg-white/5 backdrop-blur-md rounded-2xl border border-white/10 p-6">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-white/60 text-sm">Published</p>
                          <p className="text-2xl font-bold text-white">{stats.publishedProjects}</p>
                        </div>
                        <div className="w-12 h-12 bg-green-500/20 rounded-xl flex items-center justify-center">
                          <Globe className="w-6 h-6 text-green-400" />
                        </div>
                      </div>
                    </div>

                    <div className="bg-white/5 backdrop-blur-md rounded-2xl border border-white/10 p-6">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-white/60 text-sm">Total Views</p>
                          <p className="text-2xl font-bold text-white">{stats.totalViews.toLocaleString()}</p>
                        </div>
                        <div className="w-12 h-12 bg-purple-500/20 rounded-xl flex items-center justify-center">
                          <Eye className="w-6 h-6 text-purple-400" />
                        </div>
                      </div>
                    </div>

                    <div className="bg-white/5 backdrop-blur-md rounded-2xl border border-white/10 p-6">
                      <div className="flex items-center justify-between">
                        <div>
                          <p className="text-white/60 text-sm">Avg Performance</p>
                          <p className="text-2xl font-bold text-white">{stats.avgPerformance}</p>
                        </div>
                        <div className="w-12 h-12 bg-orange-500/20 rounded-xl flex items-center justify-center">
                          <Zap className="w-6 h-6 text-orange-400" />
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* Recent Projects */}
                  <div className="bg-white/5 backdrop-blur-md rounded-2xl border border-white/10 p-6">
                    <div className="flex items-center justify-between mb-6">
                      <h2 className="text-xl font-bold text-white">Recent Projects</h2>
                      <button
                        onClick={() => setActiveTab('projects')}
                        className="text-blue-400 hover:text-blue-300 text-sm font-medium"
                      >
                        View All
                      </button>
                    </div>
                    
                    <div className="space-y-4">
                      {projects.slice(0, 3).map((project) => (
                        <div
                          key={project.id}
                          className="flex items-center space-x-4 p-4 bg-white/5 rounded-xl border border-white/10 hover:bg-white/10 transition-colors"
                        >
                          <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-500 rounded-xl flex items-center justify-center">
                            <span className="text-white font-bold text-lg">
                              {project.title.charAt(0)}
                            </span>
                          </div>
                          <div className="flex-1">
                            <h3 className="font-semibold text-white">{project.title}</h3>
                            <p className="text-white/60 text-sm">{project.category}</p>
                          </div>
                          <div className="flex items-center space-x-2">
                            <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                              project.published 
                                ? 'bg-green-500/20 text-green-400' 
                                : 'bg-gray-500/20 text-gray-400'
                            }`}>
                              {project.published ? 'Published' : 'Draft'}
                            </span>
                            <button
                              onClick={() => handleEdit(project)}
                              className="p-2 text-white/60 hover:text-white hover:bg-white/10 rounded-lg transition-colors"
                            >
                              <Edit size={16} />
                            </button>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </motion.div>
              )}

              {activeTab === 'projects' && (
                <motion.div
                  key="projects"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className="space-y-6"
                >
                  <div className="flex items-center justify-between">
                    <h2 className="text-2xl font-bold text-white">Projects</h2>
                    <button
                      onClick={resetForm}
                      className="flex items-center space-x-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-xl transition-colors"
                    >
                      <Plus size={20} />
                      <span>New Project</span>
                    </button>
                  </div>

                  {isLoading ? (
                    <div className="flex items-center justify-center h-64">
                      <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500"></div>
                    </div>
                  ) : (
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                      {projects.map((project) => (
                        <div
                          key={project.id}
                          className="bg-white/5 backdrop-blur-md rounded-2xl border border-white/10 p-6 hover:bg-white/10 transition-all duration-200"
                        >
                          <div className="flex items-start justify-between mb-4">
                            <div className="w-12 h-12 bg-gradient-to-br from-blue-500 to-purple-500 rounded-xl flex items-center justify-center">
                              <span className="text-white font-bold text-lg">
                                {project.title.charAt(0)}
                              </span>
                            </div>
                            <div className="flex items-center space-x-2">
                              <button
                                onClick={() => handleEdit(project)}
                                className="p-2 text-white/60 hover:text-white hover:bg-white/10 rounded-lg transition-colors"
                              >
                                <Edit size={16} />
                              </button>
                              <button
                                onClick={() => handleDelete(project.id)}
                                className="p-2 text-white/60 hover:text-red-400 hover:bg-red-500/10 rounded-lg transition-colors"
                              >
                                <Trash2 size={16} />
                              </button>
                            </div>
                          </div>
                          
                          <h3 className="font-semibold text-white mb-2">{project.title}</h3>
                          <p className="text-white/60 text-sm mb-4 line-clamp-2">{project.description}</p>
                          
                          <div className="flex items-center justify-between">
                            <span className="px-2 py-1 bg-blue-500/20 text-blue-400 text-xs rounded-full">
                              {project.category}
                            </span>
                            <span className={`px-2 py-1 text-xs rounded-full ${
                              project.published 
                                ? 'bg-green-500/20 text-green-400' 
                                : 'bg-gray-500/20 text-gray-400'
                            }`}>
                              {project.published ? 'Published' : 'Draft'}
                            </span>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </motion.div>
              )}

              {activeTab === 'emails' && (
                <motion.div
                  key="emails"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                >
                  <EmailManager />
                </motion.div>
              )}

              {activeTab === 'analytics' && (
                <motion.div
                  key="analytics"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                >
                  <AnalyticsDashboard />
                </motion.div>
              )}

              {activeTab === 'settings' && (
                <motion.div
                  key="settings"
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className="space-y-6"
                >
                  <h2 className="text-2xl font-bold text-white">Settings</h2>
                  
                  <div className="bg-white/5 backdrop-blur-md rounded-2xl border border-white/10 p-6">
                    <h3 className="text-lg font-semibold text-white mb-4">Import/Export</h3>
                    <ImportExport />
                  </div>
                </motion.div>
              )}
            </AnimatePresence>
          </div>
        </div>
      </div>
    </div>
  );
};

export default ModernAdminDashboard;
