import React, { useState, useEffect } from 'react';
import { useNavigate, useParams, Link } from 'react-router-dom';
import MDEditor from '@uiw/react-md-editor';
import '@uiw/react-md-editor/markdown-editor.css';
import '@uiw/react-markdown-preview/markdown.css';
const API_BASE = 'https://goonblog.thevakhovske.eu.org/api';

// Note: MDEditor handles its own markdown processing for the editor interface
// The final blog rendering uses the MarkdownIt instance in App.jsx
// This separation prevents footnote duplication issues

function PostEditor() {
  const navigate = useNavigate();
  const { slug } = useParams();
  const isEditing = !!slug;

  const [formData, setFormData] = useState({
    title: '',
    description: '',
    content: '',
    tags: ''
  });
  
  const [loading, setLoading] = useState(isEditing);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (isEditing) {
      fetchPost();
    }
  }, [slug, isEditing]);

  const fetchPost = async () => {
    try {
      setLoading(true);
      const response = await fetch(`${API_BASE}/posts/${slug}`, {
        credentials: 'include'
      });
      if (!response.ok) throw new Error('Failed to fetch post');
      
      const post = await response.json();
      
      // Extract content without frontmatter
      let content = post.content;
      content = content.replace(/^title:.*$/m, '');
      content = content.replace(/^desc:.*$/m, '');
      content = content.replace(/^tags:.*$/m, '');
      content = content.replace(/^\n+/, ''); // Remove leading newlines
      
      setFormData({
        title: post.title,
        description: post.description,
        content: content.trim(),
        tags: post.tags ? post.tags.join(', ') : ''
      });
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!formData.title.trim() || !formData.content.trim()) {
      setError('Title and content are required');
      return;
    }

    try {
      setSaving(true);
      setError(null);

      const payload = {
        title: formData.title.trim(),
        description: formData.description.trim(),
        content: formData.content.trim(),
        tags: formData.tags.split(',').map(tag => tag.trim()).filter(tag => tag)
      };

      const url = isEditing 
        ? `${API_BASE}/posts/${slug}`
        : `${API_BASE}/posts`;
      
      const method = isEditing ? 'PUT' : 'POST';

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include',
        body: JSON.stringify(payload),
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || 'Failed to save post');
      }

      const savedPost = await response.json();
      navigate(`/admin`);
    } catch (err) {
      setError(err.message);
    } finally {
      setSaving(false);
    }
  };


  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-4 text-gray-600">Loading post...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
        {/* Header */}
        <div className="bg-white shadow rounded-lg mb-6">
          <div className="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
            <div>
              <h1 className="text-2xl font-bold text-gray-900">
                {isEditing ? 'Edit Post' : 'Create New Post'}
              </h1>
              <p className="text-gray-600">
                {isEditing ? 'Update your existing post' : 'Write a new blog post'}
              </p>
            </div>
            <div className="flex space-x-3">
              <Link
                to="/admin"
                className="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 transition-colors"
              >
                Back to Admin
              </Link>
            </div>
          </div>
        </div>

        {error && (
          <div className="mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
            <div className="flex">
              <div className="flex-shrink-0">
                <svg className="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                </svg>
              </div>
              <div className="ml-3">
                <h3 className="text-sm font-medium text-red-800">Error</h3>
                <p className="mt-1 text-sm text-red-700">{error}</p>
              </div>
            </div>
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Basic Info */}
          <div className="bg-white shadow rounded-lg">
            <div className="px-6 py-4 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">Post Information</h2>
            </div>
            <div className="px-6 py-4 space-y-6">
              <div>
                <label htmlFor="title" className="block text-sm font-medium text-gray-700 mb-1">
                  Title *
                </label>
                <input
                  type="text"
                  id="title"
                  required
                  value={formData.title}
                  onChange={(e) => handleInputChange('title', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="Enter post title..."
                />
              </div>

              <div>
                <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-1">
                  Description
                </label>
                <input
                  type="text"
                  id="description"
                  value={formData.description}
                  onChange={(e) => handleInputChange('description', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="Short description or excerpt..."
                />
              </div>

              <div>
                <label htmlFor="tags" className="block text-sm font-medium text-gray-700 mb-1">
                  Tags
                </label>
                <input
                  type="text"
                  id="tags"
                  value={formData.tags}
                  onChange={(e) => handleInputChange('tags', e.target.value)}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="tag1, tag2, tag3..."
                />
                <p className="mt-1 text-sm text-gray-500">Separate tags with commas</p>
              </div>
            </div>
          </div>

          {/* Content Editor */}
          <div className="bg-white shadow rounded-lg">
            <div className="px-6 py-4 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">Content</h2>
              <p className="text-sm text-gray-600 mt-1">
                Use the WYSIWYG editor below. Click the tabs to switch between Edit and Preview modes.
              </p>
            </div>
            
            <div className="px-6 py-4">
              <div className="border border-gray-300 rounded-lg overflow-hidden">
                <MDEditor
                  value={formData.content}
                  onChange={(value) => handleInputChange('content', value || '')}
                  height={500}
                  preview="edit"
                  hideToolbar={false}
                  data-color-mode="light"
                  visibleDragBar={false}
                  textareaProps={{
                    placeholder: 'Write your post content in Markdown...',
                    style: { fontSize: '14px', fontFamily: 'ui-monospace, monospace' },
                    required: true
                  }}
                />
              </div>
              <div className="mt-3 text-xs text-gray-500 bg-blue-50 p-3 rounded-lg">
                <p><strong>WYSIWYG Editor Features:</strong></p>
                <ul className="list-disc list-inside mt-1 space-y-1">
                  <li>Toggle between <strong>Edit</strong>, <strong>Preview</strong>, and <strong>Live</strong> modes using the tabs</li>
                  <li>Use toolbar buttons for quick formatting (bold, italic, headers, lists, etc.)</li>
                  <li>Standard markdown features: tables, footnotes, emoji (:emoji:), HTML support</li>
                  <li>Collapsible content: Use <code>&lt;details&gt;&lt;summary&gt;</code> HTML tags</li>
                  <li>Drag the divider to resize edit/preview panes in Live mode</li>
                </ul>
              </div>
            </div>
          </div>

          {/* Actions */}
          <div className="flex justify-end space-x-4">
            <Link
              to="/admin"
              className="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50"
            >
              Cancel
            </Link>
            <button
              type="submit"
              disabled={saving}
              className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? 'Saving...' : (isEditing ? 'Update Post' : 'Create Post')}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

export default PostEditor;