'use client';

import React, { useState, useEffect, useRef } from 'react';
import { useSearchParams } from 'next/navigation';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  ArrowLeft, 
  Save, 
  Eye, 
  Plus, 
  X, 
  Bold, 
  Italic, 
  Code, 
  Image, 
  Link,
  Type,
  List,
  ListOrdered,
  Quote,
  Hash,
  Loader2,
  Upload,
  Check
} from 'lucide-react';

interface Project {
  id: string;
  title: string;
  description: string;
  content?: string;
  category: string;
  difficulty?: string;
  tags?: string[];
  featured: boolean;
  published: boolean;
  github?: string;
  live?: string;
  image?: string;
  createdAt: string;
  updatedAt: string;
}

export default function EditorPage() {
  const searchParams = useSearchParams();
  const projectId = searchParams.get('id');
  const contentRef = useRef<HTMLDivElement>(null);
  
  const [project, setProject] = useState<Project | null>(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isCreating, setIsCreating] = useState(!projectId);
  const [showPreview, setShowPreview] = useState(false);
  
  // Form state
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    content: '',
    category: 'web',
    difficulty: 'beginner',
    tags: [] as string[],
    featured: false,
    published: false,
    github: '',
    live: '',
    image: ''
  });

  // Check authentication and load project
  useEffect(() => {
    const init = async () => {
      try {
        // Check auth
        const authStatus = sessionStorage.getItem('admin_authenticated');
        const sessionToken = sessionStorage.getItem('admin_session_token');
        
        console.log('Editor Auth check:', { authStatus, hasSessionToken: !!sessionToken, projectId });
        
        if (authStatus === 'true' && sessionToken) {
          console.log('User is authenticated');
          setIsAuthenticated(true);
          
          // Load project if editing
          if (projectId) {
            console.log('Loading project with ID:', projectId);
            await loadProject(projectId);
          } else {
            console.log('Creating new project');
            setIsCreating(true);
          }
        } else {
          console.log('User not authenticated');
          setIsAuthenticated(false);
        }
      } catch (error) {
        console.error('Error in init:', error);
        setIsAuthenticated(false);
      } finally {
        setIsLoading(false);
      }
    };

    init();
  }, [projectId]);

  const loadProject = async (id: string) => {
    try {
      console.log('Fetching projects...');
      const response = await fetch('/api/projects');
      
      if (response.ok) {
        const data = await response.json();
        console.log('Projects loaded:', data);
        
        const foundProject = data.projects.find((p: Project) => p.id.toString() === id);
        console.log('Found project:', foundProject);
        
        if (foundProject) {
          setProject(foundProject);
          setFormData({
            title: foundProject.title || '',
            description: foundProject.description || '',
            content: foundProject.content || '',
            category: foundProject.category || 'web',
            difficulty: foundProject.difficulty || 'beginner',
            tags: foundProject.tags || [],
            featured: foundProject.featured || false,
            published: foundProject.published || false,
            github: foundProject.github || '',
            live: foundProject.live || '',
            image: foundProject.image || ''
          });
          console.log('Form data set:', formData);
        } else {
          console.log('Project not found with ID:', id);
        }
      } else {
        console.error('Failed to fetch projects:', response.status);
      }
    } catch (error) {
      console.error('Error loading project:', error);
    }
  };

  const handleSave = async () => {
    try {
      setIsSaving(true);
      
      const url = projectId ? `/api/projects/${projectId}` : '/api/projects';
      const method = projectId ? 'PUT' : 'POST';
      
      console.log('Saving project:', { url, method, formData });
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
      });

      if (response.ok) {
        const savedProject = await response.json();
        console.log('Project saved:', savedProject);
        
        // Show success and redirect
        setTimeout(() => {
          window.location.href = '/manage';
        }, 1000);
      } else {
        console.error('Error saving project:', response.status);
        alert('Error saving project');
      }
    } catch (error) {
      console.error('Error saving project:', error);
      alert('Error saving project');
    } finally {
      setIsSaving(false);
    }
  };

  const handleInputChange = (field: string, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const handleTagsChange = (tagsString: string) => {
    const tags = tagsString.split(',').map(tag => tag.trim()).filter(tag => tag);
    setFormData(prev => ({
      ...prev,
      tags
    }));
  };

  // Rich text editor functions
  const insertFormatting = (format: string) => {
    const content = contentRef.current;
    if (!content) return;

    const selection = window.getSelection();
    if (!selection || selection.rangeCount === 0) return;

    const range = selection.getRangeAt(0);
    let newText = '';
    
    switch (format) {
      case 'bold':
        newText = `**${selection.toString() || 'bold text'}**`;
        break;
      case 'italic':
        newText = `*${selection.toString() || 'italic text'}*`;
        break;
      case 'code':
        newText = `\`${selection.toString() || 'code'}\``;
        break;
      case 'h1':
        newText = `# ${selection.toString() || 'Heading 1'}`;
        break;
      case 'h2':
        newText = `## ${selection.toString() || 'Heading 2'}`;
        break;
      case 'h3':
        newText = `### ${selection.toString() || 'Heading 3'}`;
        break;
      case 'list':
        newText = `- ${selection.toString() || 'List item'}`;
        break;
      case 'orderedList':
        newText = `1. ${selection.toString() || 'List item'}`;
        break;
      case 'quote':
        newText = `> ${selection.toString() || 'Quote'}`;
        break;
      case 'link':
        const url = prompt('Enter URL:');
        if (url) {
          newText = `[${selection.toString() || 'link text'}](${url})`;
        }
        break;
      case 'image':
        const imageUrl = prompt('Enter image URL:');
        if (imageUrl) {
          newText = `![${selection.toString() || 'alt text'}](${imageUrl})`;
        }
        break;
    }

    if (newText) {
      range.deleteContents();
      range.insertNode(document.createTextNode(newText));
      
      // Update form data
      setFormData(prev => ({
        ...prev,
        content: content.textContent || ''
      }));
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen admin-gradient flex items-center justify-center">
        <div className="text-center">
          <motion.div
            animate={{ rotate: 360 }}
            transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
            className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full mx-auto mb-4"
          />
          <p className="text-white">Loading editor...</p>
        </div>
      </div>
    );
  }

  if (!isAuthenticated) {
    return (
      <div className="min-h-screen admin-gradient flex items-center justify-center">
        <motion.div 
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          className="text-center text-white max-w-md mx-auto p-8 admin-glass-card rounded-2xl"
        >
          <div className="mb-6">
            <div className="w-16 h-16 bg-red-500/20 rounded-full flex items-center justify-center mx-auto mb-4">
              <X className="w-8 h-8 text-red-400" />
            </div>
            <h1 className="text-2xl font-bold mb-2">Access Denied</h1>
            <p className="text-white/70 mb-6">You need to be logged in to access the editor.</p>
          </div>
          
          <button
            onClick={() => window.location.href = '/manage'}
            className="w-full px-6 py-3 bg-gradient-to-r from-blue-500 to-purple-500 text-white rounded-xl hover:scale-105 transition-all font-medium"
          >
            Go to Admin Login
          </button>
        </motion.div>
      </div>
    );
  }

  return (
    <div className="min-h-screen admin-gradient">
      {/* Header */}
      <div className="admin-glass-header border-b border-white/10">
        <div className="max-w-7xl mx-auto px-6">
          <div className="flex items-center justify-between h-16">
            <div className="flex items-center space-x-4">
              <button
                onClick={() => window.location.href = '/manage'}
                className="flex items-center space-x-2 text-white/70 hover:text-white transition-colors"
              >
                <ArrowLeft className="w-5 h-5" />
                <span>Back to Dashboard</span>
              </button>
              <div className="h-6 w-px bg-white/20" />
              <h1 className="text-xl font-semibold text-white">
                {isCreating ? 'Create New Project' : `Edit: ${formData.title || 'Untitled'}`}
              </h1>
            </div>
            
            <div className="flex items-center space-x-3">
              <button
                onClick={() => setShowPreview(!showPreview)}
                className={`flex items-center space-x-2 px-4 py-2 rounded-xl transition-all ${
                  showPreview 
                    ? 'bg-purple-500 text-white' 
                    : 'bg-white/10 text-white/70 hover:bg-white/20'
                }`}
              >
                <Eye className="w-4 h-4" />
                <span>Preview</span>
              </button>
              
              <button
                onClick={handleSave}
                disabled={isSaving}
                className="flex items-center space-x-2 px-6 py-2 bg-gradient-to-r from-blue-500 to-purple-500 text-white rounded-xl hover:scale-105 transition-all font-medium disabled:opacity-50"
              >
                {isSaving ? (
                  <Loader2 className="w-4 h-4 animate-spin" />
                ) : (
                  <Save className="w-4 h-4" />
                )}
                <span>{isSaving ? 'Saving...' : 'Save Project'}</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Editor Content */}
      <div className="max-w-7xl mx-auto px-6 py-8">
        <div className="grid grid-cols-1 xl:grid-cols-4 gap-8">
          {/* Main Editor */}
          <div className="xl:col-span-3 space-y-6">
            {/* Project Title */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="admin-glass-card p-6 rounded-xl"
            >
              <input
                type="text"
                value={formData.title}
                onChange={(e) => handleInputChange('title', e.target.value)}
                className="w-full text-3xl font-bold bg-white/10 text-white placeholder-white/50 focus:outline-none p-4 rounded-lg border border-white/20 focus:ring-2 focus:ring-blue-500"
                placeholder="Enter project title..."
              />
            </motion.div>

            {/* Rich Text Toolbar */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.1 }}
              className="admin-glass-card p-4 rounded-xl"
            >
              <div className="flex flex-wrap items-center gap-2">
                <div className="flex items-center space-x-1 border-r border-white/20 pr-3">
                  <button
                    onClick={() => insertFormatting('bold')}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                    title="Bold"
                  >
                    <Bold className="w-4 h-4 text-white/70" />
                  </button>
                  <button
                    onClick={() => insertFormatting('italic')}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                    title="Italic"
                  >
                    <Italic className="w-4 h-4 text-white/70" />
                  </button>
                  <button
                    onClick={() => insertFormatting('code')}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                    title="Code"
                  >
                    <Code className="w-4 h-4 text-white/70" />
                  </button>
                </div>

                <div className="flex items-center space-x-1 border-r border-white/20 pr-3">
                  <button
                    onClick={() => insertFormatting('h1')}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                    title="Heading 1"
                  >
                    <Hash className="w-4 h-4 text-white/70" />
                  </button>
                  <button
                    onClick={() => insertFormatting('h2')}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors text-sm"
                    title="Heading 2"
                  >
                    H2
                  </button>
                  <button
                    onClick={() => insertFormatting('h3')}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors text-sm"
                    title="Heading 3"
                  >
                    H3
                  </button>
                </div>

                <div className="flex items-center space-x-1 border-r border-white/20 pr-3">
                  <button
                    onClick={() => insertFormatting('list')}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                    title="Bullet List"
                  >
                    <List className="w-4 h-4 text-white/70" />
                  </button>
                  <button
                    onClick={() => insertFormatting('orderedList')}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                    title="Numbered List"
                  >
                    <ListOrdered className="w-4 h-4 text-white/70" />
                  </button>
                  <button
                    onClick={() => insertFormatting('quote')}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                    title="Quote"
                  >
                    <Quote className="w-4 h-4 text-white/70" />
                  </button>
                </div>

                <div className="flex items-center space-x-1">
                  <button
                    onClick={() => insertFormatting('link')}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                    title="Link"
                  >
                    <Link className="w-4 h-4 text-white/70" />
                  </button>
                  <button
                    onClick={() => insertFormatting('image')}
                    className="p-2 hover:bg-white/10 rounded-lg transition-colors"
                    title="Image"
                  >
                    <Image className="w-4 h-4 text-white/70" />
                  </button>
                </div>
              </div>
            </motion.div>

            {/* Content Editor */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
              className="admin-glass-card p-6 rounded-xl"
            >
              <h3 className="text-lg font-semibold text-white mb-4">Content</h3>
              <div
                ref={contentRef}
                contentEditable
                className="w-full min-h-[400px] p-6 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-blue-500 leading-relaxed"
                style={{ whiteSpace: 'pre-wrap' }}
                onInput={(e) => {
                  const target = e.target as HTMLDivElement;
                  setFormData(prev => ({
                    ...prev,
                    content: target.textContent || ''
                  }));
                }}
                suppressContentEditableWarning={true}
              >
                {formData.content || 'Start writing your project content...'}
              </div>
              <p className="text-xs text-white/50 mt-2">
                Supports Markdown formatting. Use the toolbar above or type directly.
              </p>
            </motion.div>

            {/* Description */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
              className="admin-glass-card p-6 rounded-xl"
            >
              <h3 className="text-lg font-semibold text-white mb-4">Description</h3>
              <textarea
                value={formData.description}
                onChange={(e) => handleInputChange('description', e.target.value)}
                rows={4}
                className="w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                placeholder="Brief description of your project..."
              />
            </motion.div>
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            {/* Project Settings */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.4 }}
              className="admin-glass-card p-6 rounded-xl"
            >
              <h3 className="text-lg font-semibold text-white mb-4">Settings</h3>
              
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-white/70 mb-2">
                    Category
                  </label>
                  <select
                    value={formData.category}
                    onChange={(e) => handleInputChange('category', e.target.value)}
                    className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="web">Web Development</option>
                    <option value="mobile">Mobile Development</option>
                    <option value="desktop">Desktop Application</option>
                    <option value="game">Game Development</option>
                    <option value="ai">AI/ML</option>
                    <option value="other">Other</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-white/70 mb-2">
                    Difficulty
                  </label>
                  <select
                    value={formData.difficulty}
                    onChange={(e) => handleInputChange('difficulty', e.target.value)}
                    className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                  >
                    <option value="beginner">Beginner</option>
                    <option value="intermediate">Intermediate</option>
                    <option value="advanced">Advanced</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium text-white/70 mb-2">
                    Tags
                  </label>
                  <input
                    type="text"
                    value={formData.tags.join(', ')}
                    onChange={(e) => handleTagsChange(e.target.value)}
                    className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="React, TypeScript, Next.js"
                  />
                </div>
              </div>
            </motion.div>

            {/* Links */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.5 }}
              className="admin-glass-card p-6 rounded-xl"
            >
              <h3 className="text-lg font-semibold text-white mb-4">Links</h3>
              
              <div className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-white/70 mb-2">
                    GitHub URL
                  </label>
                  <input
                    type="url"
                    value={formData.github}
                    onChange={(e) => handleInputChange('github', e.target.value)}
                    className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="https://github.com/username/repo"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-white/70 mb-2">
                    Live URL
                  </label>
                  <input
                    type="url"
                    value={formData.live}
                    onChange={(e) => handleInputChange('live', e.target.value)}
                    className="w-full px-3 py-2 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="https://example.com"
                  />
                </div>
              </div>
            </motion.div>

            {/* Publish */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.6 }}
              className="admin-glass-card p-6 rounded-xl"
            >
              <h3 className="text-lg font-semibold text-white mb-4">Publish</h3>
              
              <div className="space-y-4">
                <label className="flex items-center space-x-3">
                  <input
                    type="checkbox"
                    checked={formData.featured}
                    onChange={(e) => handleInputChange('featured', e.target.checked)}
                    className="w-4 h-4 text-blue-500 bg-white/10 border-white/20 rounded focus:ring-blue-500"
                  />
                  <span className="text-white">Featured Project</span>
                </label>

                <label className="flex items-center space-x-3">
                  <input
                    type="checkbox"
                    checked={formData.published}
                    onChange={(e) => handleInputChange('published', e.target.checked)}
                    className="w-4 h-4 text-blue-500 bg-white/10 border-white/20 rounded focus:ring-blue-500"
                  />
                  <span className="text-white">Published</span>
                </label>
              </div>

              <div className="mt-6 pt-4 border-t border-white/20">
                <h4 className="text-sm font-medium text-white/70 mb-2">Preview</h4>
                <div className="text-xs text-white/50 space-y-1">
                  <p>Status: {formData.published ? 'Published' : 'Draft'}</p>
                  {formData.featured && <p className="text-blue-400">⭐ Featured</p>}
                  <p>Category: {formData.category}</p>
                  <p>Tags: {formData.tags.length} tags</p>
                </div>
              </div>
            </motion.div>
          </div>
        </div>
      </div>
    </div>
  );
}