import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import AdminLayout from '../../components/AdminLayout';
import { getBlogPost, createBlogPost, updateBlogPost } from '../../utils/api';
import axios from 'axios';

const BACKEND_URL = process.env.REACT_APP_BACKEND_URL;

const AdminBlogEditor = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const isEditMode = Boolean(id);

  const [formData, setFormData] = useState({
    title: '',
    slug: '',
    content: '',
    excerpt: '',
    meta_description: '',
    meta_keywords: '',
    author: 'Tim RH Elektronik',
    featured_image: '',
    status: 'draft'
  });
  const [loading, setLoading] = useState(isEditMode);
  const [saving, setSaving] = useState(false);
  const [uploadingImage, setUploadingImage] = useState(false);
  const [showPreview, setShowPreview] = useState(false);

  useEffect(() => {
    if (isEditMode) {
      loadPost();
    }
  }, [id]);

  const loadPost = async () => {
    try {
      const response = await getBlogPost(id);
      setFormData(response.data);
    } catch (error) {
      alert('Failed to load post');
      navigate('/admin/blogs');
    } finally {
      setLoading(false);
    }
  };

  // Upload image function
  const uploadImage = async (file) => {
    setUploadingImage(true);
    try {
      const formDataUpload = new FormData();
      formDataUpload.append('file', file);

      const token = localStorage.getItem('admin_token');
      const response = await axios.post(`${BACKEND_URL}/api/upload-image`, formDataUpload, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${token}`
        }
      });

      return response.data.url;
    } catch (error) {
      alert('Failed to upload image: ' + (error.response?.data?.detail || error.message));
      return null;
    } finally {
      setUploadingImage(false);
    }
  };

  // Featured image upload handler
  const handleFeaturedImageUpload = async (e) => {
    const file = e.target.files[0];
    if (file) {
      const imageUrl = await uploadImage(file);
      if (imageUrl) {
        setFormData(prev => ({ ...prev, featured_image: imageUrl }));
      }
    }
  };

  // Insert image in content at cursor position
  const handleContentImageUpload = async (e) => {
    const file = e.target.files[0];
    if (file) {
      const imageUrl = await uploadImage(file);
      if (imageUrl) {
        const textarea = document.getElementById('content-editor');
        const cursorPos = textarea.selectionStart;
        const textBefore = formData.content.substring(0, cursorPos);
        const textAfter = formData.content.substring(cursorPos);
        
        const imageHtml = `\n<img src="${imageUrl}" alt="Image" style="max-width: 100%; height: auto; border-radius: 8px; margin: 1rem 0;" />\n`;
        
        setFormData(prev => ({
          ...prev,
          content: textBefore + imageHtml + textAfter
        }));
      }
    }
  };

  // Formatting helpers
  const insertFormatting = (before, after = '') => {
    const textarea = document.getElementById('content-editor');
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const selectedText = formData.content.substring(start, end);
    
    const newText = formData.content.substring(0, start) + 
                    before + selectedText + after + 
                    formData.content.substring(end);
    
    setFormData(prev => ({ ...prev, content: newText }));
    
    // Restore focus and selection
    setTimeout(() => {
      textarea.focus();
      const newCursorPos = start + before.length + selectedText.length;
      textarea.setSelectionRange(newCursorPos, newCursorPos);
    }, 0);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSaving(true);

    try {
      if (isEditMode) {
        await updateBlogPost(id, formData);
      } else {
        await createBlogPost(formData);
      }
      navigate('/admin/blogs');
    } catch (error) {
      alert('Failed to save post');
    } finally {
      setSaving(false);
    }
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  if (loading) {
    return (
      <AdminLayout>
        <div className="text-center py-20">Loading...</div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <div className="mb-8">
        <h1 className="text-3xl font-extrabold text-gray-900">
          {isEditMode ? 'Edit Blog Post' : 'New Blog Post'}
        </h1>
        <p className="text-gray-600 mt-2">✨ Editor seperti Microsoft Word untuk menulis artikel yang menarik</p>
      </div>

      <form onSubmit={handleSubmit} className="bg-white rounded-2xl shadow-sm border border-gray-200 p-8">
        <div className="space-y-6">
          {/* Title */}
          <div>
            <label className="block text-gray-700 font-semibold mb-2">
              📝 Judul Artikel *
            </label>
            <input 
              type="text"
              name="title"
              value={formData.title}
              onChange={handleChange}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 text-lg font-semibold"
              required
              placeholder="Masukkan judul artikel yang menarik..."
              data-testid="title-input"
            />
          </div>

          {/* Excerpt */}
          <div>
            <label className="block text-gray-700 font-semibold mb-2">
              📄 Ringkasan Singkat
            </label>
            <textarea 
              name="excerpt"
              value={formData.excerpt}
              onChange={handleChange}
              rows="2"
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="Ringkasan artikel untuk ditampilkan di halaman daftar blog (150-200 karakter)..."
            />
          </div>

          {/* SEO Section */}
          <div className="bg-gradient-to-r from-green-50 to-blue-50 border-2 border-green-200 rounded-xl p-6">
            <h3 className="font-bold text-green-900 mb-4 text-lg">🚀 SEO Settings (Optimasi Google)</h3>
            
            <div className="space-y-4">
              {/* Meta Description */}
              <div>
                <label className="block text-gray-700 font-semibold mb-2">
                  📝 Meta Description *
                </label>
                <textarea 
                  name="meta_description"
                  value={formData.meta_description}
                  onChange={handleChange}
                  rows="2"
                  maxLength="160"
                  className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-green-500"
                  placeholder="Deskripsi untuk Google Search (160 karakter)..."
                />
                <p className="text-sm text-gray-500 mt-1">
                  {formData.meta_description.length}/160 karakter
                </p>
              </div>

              {/* Keywords */}
              <div>
                <label className="block text-gray-700 font-semibold mb-2">
                  🏷️ Keywords SEO
                </label>
                <input 
                  type="text"
                  name="meta_keywords"
                  value={formData.meta_keywords}
                  onChange={handleChange}
                  className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-green-500"
                  placeholder="tips ac, service, elektronik, perawatan"
                />
              </div>
            </div>
          </div>

          {/* Rich Text Editor Toolbar */}
          <div>
            <label className="block text-gray-700 font-semibold mb-2">
              ✍️ Konten Artikel * {uploadingImage && <span className="text-blue-600 animate-pulse">(Uploading...)</span>}
            </label>
            
            {/* Formatting Toolbar */}
            <div className="bg-gray-50 border border-gray-300 rounded-t-xl p-3 flex flex-wrap gap-2">
              <button
                type="button"
                onClick={() => insertFormatting('<h2>', '</h2>')}
                className="px-3 py-1 bg-white border border-gray-300 rounded hover:bg-gray-100 font-bold"
                title="Heading 2"
              >
                H2
              </button>
              <button
                type="button"
                onClick={() => insertFormatting('<h3>', '</h3>')}
                className="px-3 py-1 bg-white border border-gray-300 rounded hover:bg-gray-100 font-semibold"
                title="Heading 3"
              >
                H3
              </button>
              <div className="w-px bg-gray-300"></div>
              <button
                type="button"
                onClick={() => insertFormatting('<strong>', '</strong>')}
                className="px-3 py-1 bg-white border border-gray-300 rounded hover:bg-gray-100 font-bold"
                title="Bold"
              >
                <strong>B</strong>
              </button>
              <button
                type="button"
                onClick={() => insertFormatting('<em>', '</em>')}
                className="px-3 py-1 bg-white border border-gray-300 rounded hover:bg-gray-100 italic"
                title="Italic"
              >
                <em>I</em>
              </button>
              <button
                type="button"
                onClick={() => insertFormatting('<u>', '</u>')}
                className="px-3 py-1 bg-white border border-gray-300 rounded hover:bg-gray-100 underline"
                title="Underline"
              >
                U
              </button>
              <div className="w-px bg-gray-300"></div>
              <button
                type="button"
                onClick={() => insertFormatting('<p>', '</p>')}
                className="px-3 py-1 bg-white border border-gray-300 rounded hover:bg-gray-100"
                title="Paragraph"
              >
                ¶
              </button>
              <button
                type="button"
                onClick={() => insertFormatting('<ul>\n<li>', '</li>\n</ul>')}
                className="px-3 py-1 bg-white border border-gray-300 rounded hover:bg-gray-100"
                title="Bullet List"
              >
                • List
              </button>
              <button
                type="button"
                onClick={() => insertFormatting('<a href="">', '</a>')}
                className="px-3 py-1 bg-white border border-gray-300 rounded hover:bg-gray-100 text-blue-600"
                title="Link"
              >
                🔗 Link
              </button>
              <div className="w-px bg-gray-300"></div>
              <label className="px-3 py-1 bg-green-500 text-white border border-green-600 rounded hover:bg-green-600 cursor-pointer font-semibold">
                📷 Upload Gambar
                <input 
                  type="file"
                  accept="image/*"
                  onChange={handleContentImageUpload}
                  className="hidden"
                />
              </label>
              <button
                type="button"
                onClick={() => setShowPreview(!showPreview)}
                className={`px-3 py-1 border rounded font-semibold ${
                  showPreview 
                    ? 'bg-blue-600 text-white border-blue-700' 
                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-100'
                }`}
              >
                {showPreview ? '✏️ Edit' : '👁️ Preview'}
              </button>
            </div>

            {/* Content Editor / Preview */}
            {showPreview ? (
              <div className="border border-gray-300 border-t-0 rounded-b-xl p-6 min-h-[400px] bg-white blog-content">
                <h2 className="text-2xl font-bold mb-4 text-gray-900">{formData.title || 'Preview Artikel'}</h2>
                <div dangerouslySetInnerHTML={{ __html: formData.content || '<p className="text-gray-400">Konten akan muncul di sini...</p>' }} />
              </div>
            ) : (
              <textarea 
                id="content-editor"
                name="content"
                value={formData.content}
                onChange={handleChange}
                rows="20"
                className="w-full px-4 py-3 border border-gray-300 border-t-0 rounded-b-xl focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm"
                required
                placeholder="<p>Mulai menulis artikel Anda di sini...</p>\n\n<h3>Contoh Heading 3</h3>\n<p>Gunakan HTML tags untuk formatting. Contoh:</p>\n<ul>\n  <li>Paragraf: <p>text</p></li>\n  <li>Bold: <strong>text</strong></li>\n  <li>List: <ul><li>item</li></ul></li>\n</ul>"
                data-testid="content-input"
              />
            )}
            <p className="text-sm text-gray-500 mt-2">
              💡 <strong>Tips:</strong> Gunakan toolbar di atas untuk formatting. Klik "Upload Gambar" untuk menambahkan gambar ke artikel.
            </p>
          </div>

          {/* Author */}
          <div>
            <label className="block text-gray-700 font-semibold mb-2">
              👤 Penulis
            </label>
            <input 
              type="text"
              name="author"
              value={formData.author}
              onChange={handleChange}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>

          {/* Featured Image */}
          <div>
            <label className="block text-gray-700 font-semibold mb-2">
              🖼️ Gambar Unggulan (Featured Image)
            </label>
            <div className="grid md:grid-cols-2 gap-4">
              <div>
                <label className="block w-full px-4 py-3 border-2 border-dashed border-gray-300 rounded-xl hover:border-blue-500 cursor-pointer text-center transition">
                  <div className="text-blue-600 font-semibold mb-1">📤 Upload Gambar</div>
                  <div className="text-sm text-gray-500">Klik untuk pilih gambar dari komputer</div>
                  <input 
                    type="file"
                    accept="image/*"
                    onChange={handleFeaturedImageUpload}
                    className="hidden"
                  />
                </label>
              </div>
              <div>
                <input 
                  type="url"
                  name="featured_image"
                  value={formData.featured_image}
                  onChange={handleChange}
                  className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="Atau masukkan URL gambar"
                />
                <p className="text-xs text-gray-500 mt-1">Contoh: https://images.unsplash.com/...</p>
              </div>
            </div>
            {formData.featured_image && (
              <div className="mt-4">
                <p className="text-sm text-gray-600 mb-2 font-semibold">Preview Gambar Unggulan:</p>
                <img 
                  src={formData.featured_image}
                  alt="Preview"
                  className="w-full max-w-2xl h-64 object-cover rounded-xl border-2 border-gray-300 shadow-md"
                  onError={(e) => {
                    e.target.style.display = 'none';
                  }}
                />
              </div>
            )}
          </div>

          {/* Status */}
          <div>
            <label className="block text-gray-700 font-semibold mb-2">
              📌 Status Publikasi
            </label>
            <select 
              name="status"
              value={formData.status}
              onChange={handleChange}
              className="w-full px-4 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500 font-semibold"
              data-testid="status-select"
            >
              <option value="draft">📝 Draft - Simpan dulu, publish nanti</option>
              <option value="published">✅ Published - Tampilkan di website sekarang</option>
            </select>
          </div>
        </div>

        {/* Actions */}
        <div className="flex gap-4 mt-8 pt-6 border-t">
          <button 
            type="submit"
            disabled={saving || uploadingImage}
            className="bg-blue-600 text-white px-8 py-3 rounded-xl font-bold hover:bg-blue-700 transition disabled:opacity-50 disabled:cursor-not-allowed shadow-lg"
            data-testid="save-button"
          >
            {saving ? '💾 Menyimpan...' : (isEditMode ? '✏️ Update Artikel' : '✨ Buat Artikel Baru')}
          </button>
          <button 
            type="button"
            onClick={() => navigate('/admin/blogs')}
            className="bg-gray-200 text-gray-700 px-8 py-3 rounded-xl font-bold hover:bg-gray-300 transition"
          >
            ← Batal
          </button>
          {isEditMode && formData.status === 'published' && (
            <a 
              href={`/blog/${id}`}
              target="_blank"
              rel="noopener noreferrer"
              className="bg-green-600 text-white px-8 py-3 rounded-xl font-bold hover:bg-green-700 transition shadow-lg"
            >
              👁️ Lihat di Website
            </a>
          )}
        </div>
      </form>

      {/* Help Section */}
      <div className="mt-6 bg-gradient-to-r from-blue-50 to-purple-50 border-2 border-blue-200 rounded-2xl p-6">
        <h3 className="font-bold text-blue-900 mb-4 text-lg">💡 Panduan Menulis Artikel yang Menarik</h3>
        <div className="grid md:grid-cols-2 gap-4">
          <div>
            <h4 className="font-semibold text-blue-800 mb-2">✅ Yang Harus Dilakukan:</h4>
            <ul className="space-y-1 text-sm text-blue-700">
              <li>• Gunakan judul yang jelas dan menarik</li>
              <li>• Upload gambar berkualitas tinggi</li>
              <li>• Gunakan heading (H2, H3) untuk struktur</li>
              <li>• Tambahkan gambar di dalam artikel</li>
              <li>• Tulis ringkasan yang singkat dan jelas</li>
            </ul>
          </div>
          <div>
            <h4 className="font-semibold text-purple-800 mb-2">📋 HTML Tags yang Berguna:</h4>
            <ul className="space-y-1 text-sm text-purple-700 font-mono">
              <li>• &lt;h2&gt;Judul Besar&lt;/h2&gt;</li>
              <li>• &lt;h3&gt;Judul Sedang&lt;/h3&gt;</li>
              <li>• &lt;p&gt;Paragraf text&lt;/p&gt;</li>
              <li>• &lt;strong&gt;Tebal&lt;/strong&gt;</li>
              <li>• &lt;ul&gt;&lt;li&gt;List item&lt;/li&gt;&lt;/ul&gt;</li>
            </ul>
          </div>
        </div>
      </div>
    </AdminLayout>
  );
};

export default AdminBlogEditor;
