// D:\Nextjs\latest-deployed-universitiespage-code\src\app\pages\News\AddNews\AddNews.jsx

'use client';

import { useState, useEffect } from 'react';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { 
  Plus, 
  Trash2, 
  Star, 
  Loader2, 
  ChevronLeft, 
  ChevronRight, 
  Save,
  X,
  User,
  Users
} from 'lucide-react';

const SummernoteEditor = dynamic(
  () => import('../../../components/organisms/SummernoteEditor'),
  { 
    ssr: false,
    loading: () => <div className="border rounded-md p-4">Loading editor...</div>
  }
);

const tabs = [
  'BASIC INFO',
  'CONTENT',
  'SCHEMA',
  'META TAGS',
  'SETTINGS'
];

const initialForm = {
  title: '',
  slug: '',
  author_id: '',
  description: '',
  image: '',
  is_featured: false,
  is_active: true,
  sm_question: JSON.stringify(['']),
  sm_answer: JSON.stringify(['']),
  seo: '{}',
  enable_meta_tags: false,
  meta_title: '',
  meta_description: '',
  meta_keywords: '',
  likes: 0,
};

export default function AddNews({ id = null, isEditMode = false, initialData = null, onSuccess = null }) {
  const router = useRouter();
  const [form, setForm] = useState(initialData || initialForm);
  const [loading, setLoading] = useState(false);
  const [authors, setAuthors] = useState([]);
  const [showAuthorDropdown, setShowAuthorDropdown] = useState(false);
  const [imageUploading, setImageUploading] = useState(false);
  const [activeTab, setActiveTab] = useState('BASIC INFO');
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  useEffect(() => {
    loadAuthors();
    if (isEditMode && id && !initialData) {
      loadNews();
    }
  }, [id, isEditMode, initialData]);

  // Load authors from API
  const loadAuthors = async () => {
    try {
      const res = await fetch('/api/internal/blogs/authors');
      const data = await res.json();
      
      if (data.success) {
        setAuthors(data.data);
      } else {
        toast.error(data.message || 'Failed to load authors');
      }
    } catch (error) {
      console.error('Error loading authors:', error);
      toast.error('Failed to load authors');
    }
  };

  // Get selected author name
  const getSelectedAuthorName = () => {
    if (!form.author_id) return 'Select Author';
    const author = authors.find(a => a.id == form.author_id);
    return author ? author.full_name : 'Select Author';
  };

  // Helper function to safely get string values
  const safeString = (value) => {
    return value !== null && value !== undefined ? String(value) : '';
  };

  // Helper function to safely get boolean values
  const safeBool = (value) => {
    return Boolean(value);
  };

  // Helper function to safely get number values
  const safeNumber = (value) => {
    const num = Number(value);
    return isNaN(num) ? 0 : num;
  };

  const loadNews = async () => {
    try {
      setLoading(true);
      const res = await fetch(`/api/internal/news/${id}`);
      
      if (!res.ok) {
        throw new Error('Failed to fetch news');
      }

      const data = await res.json();
      
      if (!data?.success || !data?.data) {
        throw new Error(data?.message || 'News not found');
      }

      const news = data.data;
      
      const parseJsonField = (field, defaultValue) => {
        try {
          return field ? JSON.parse(field) : defaultValue;
        } catch {
          return defaultValue;
        }
      };

      const seoData = parseJsonField(news.seo, {});
      const smQuestion = parseJsonField(news.sm_question, ['']);
      const smAnswer = parseJsonField(news.sm_answer, ['']);

      // Safely set form data with proper type conversions
      setForm({
        title: safeString(news.title),
        slug: safeString(news.slug),
        author_id: safeString(news.author_id || ''),
        description: safeString(news.description),
        image: safeString(news.image),
        is_featured: safeBool(news.is_featured),
        is_active: safeBool(news.is_active),
        sm_question: JSON.stringify(smQuestion),
        sm_answer: JSON.stringify(smAnswer),
        seo: safeString(news.seo || '{}'),
        enable_meta_tags: safeBool(news.enable_meta_tags),
        meta_title: safeString(seoData.meta_title || news.meta_title),
        meta_description: safeString(seoData.meta_description || news.meta_description),
        meta_keywords: safeString(seoData.meta_keywords || news.meta_keywords),
      });
    } catch (error) {
      console.error('Error loading news:', error);
      toast.error(error.message || 'Failed to load news');
      router.push('/admin/news');
    } finally {
      setLoading(false);
    }
  };

  // Handle author selection
  const handleAuthorSelect = (authorId) => {
    setForm(prev => ({ ...prev, author_id: String(authorId) }));
    setShowAuthorDropdown(false);
  };

  // Clear author selection
  const handleClearAuthor = () => {
    setForm(prev => ({ ...prev, author_id: '' }));
  };

  const addSchemaRow = () => {
    const questions = JSON.parse(form.sm_question);
    const answers = JSON.parse(form.sm_answer);
    questions.push('');
    answers.push('');
    setForm(prev => ({
      ...prev,
      sm_question: JSON.stringify(questions),
      sm_answer: JSON.stringify(answers),
    }));
  };

  const removeSchemaRow = (index) => {
    const questions = JSON.parse(form.sm_question);
    const answers = JSON.parse(form.sm_answer);
    if (questions.length > 1) {
      questions.splice(index, 1);
      answers.splice(index, 1);
      setForm(prev => ({
        ...prev,
        sm_question: JSON.stringify(questions),
        sm_answer: JSON.stringify(answers),
      }));
    }
  };

  const handleSchemaChange = (index, field, value) => {
    const questions = JSON.parse(form.sm_question);
    const answers = JSON.parse(form.sm_answer);
    if (field === 'question') questions[index] = safeString(value);
    else answers[index] = safeString(value);
    setForm(prev => ({
      ...prev,
      sm_question: JSON.stringify(questions),
      sm_answer: JSON.stringify(answers),
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!form.title || !form.slug) {
      toast.error('Please fill all required fields');
      return;
    }

    try {
      setLoading(true);

      const payload = {
        ...form,
        seo: JSON.stringify({
          meta_title: form.meta_title,
          meta_description: form.meta_description,
          meta_keywords: form.meta_keywords,
        }),
        author_id: form.author_id ? Number(form.author_id) : null,
      };

      const url = isEditMode ? `/api/internal/news/${id}` : '/api/internal/news';
      const method = isEditMode ? 'PUT' : 'POST';

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

      let data;
      try {
        if (!res.ok) {
          const errorText = await res.text();
          throw new Error(`Request failed: ${res.status} ${res.statusText}\n${errorText}`);
        }
        data = await res.json();
      } catch (err) {
        toast.error('Server error or invalid response');
        console.error('Fetch error:', err);
        setLoading(false);
        return;
      }
      
      if (data.success) {
        toast.success(`News ${isEditMode ? 'updated' : 'created'} successfully!`);
        if (onSuccess) {
          onSuccess();
        } else {
          router.push('/admin/news');
        }
      } else {
        toast.error(data.message || `Failed to ${isEditMode ? 'update' : 'create'} news`);
      }
    } catch (error) {
      console.error('Error submitting news:', error);
      toast.error(`Error ${isEditMode ? 'updating' : 'creating'} news`);
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    const { name, value, type, checked } = e.target;
    setForm(prev => ({ 
      ...prev, 
      [name]: type === 'checkbox' ? checked : safeString(value)
    }));
  };

  const handleTitleChange = (e) => {
    const title = safeString(e.target.value);
    setForm(prev => ({ 
      ...prev, 
      title, 
      slug: isEditMode ? form.slug : generateSlug(title) 
    }));
  };

  const generateSlug = (text) => {
    return safeString(text)
      .toLowerCase()
      .replace(/[^\w\s-]/g, '')
      .replace(/\s+/g, '-')
      .replace(/--+/g, '-')
      .trim();
  };

  const handleDescriptionChange = (html) => {
    setForm(prev => {
      const newForm = { ...prev, description: safeString(html) };
      return newForm;
    });
  };

  const handleImageChange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    try {
      setImageUploading(true);
      const formData = new FormData();
      formData.append('image', file);
      formData.append('uploadType', 'news-featured');

      const res = await fetch('/api/internal/upload', {
        method: 'POST',
        body: formData,
      });

      const data = await res.json();
      
      if (data.success && data.url) {
        setForm(prev => ({ 
          ...prev, 
          image: safeString(data.s3Key)
        }));
        toast.success('Image uploaded successfully');
      } else {
        toast.error(data.message || 'Image upload failed');
      }
    } catch (error) {
      toast.error('Image upload error');
      console.error('Upload error:', error);
    } finally {
      setImageUploading(false);
    }
  };

  const renderContent = () => {
    switch (activeTab) {
      case 'BASIC INFO':
        return (
          <div className="space-y-4">
            <div className="space-y-2">
              <label className="block font-medium">
                News Title <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                name="title"
                value={form.title}
                onChange={handleTitleChange}
                required
                className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent transition-all"
                placeholder="Enter news title"
                disabled={loading}
              />
            </div>

            <div className="space-y-2">
              <label className="block font-medium">
                Slug <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                name="slug"
                value={form.slug}
                onChange={handleChange}
                required
                className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent transition-all"
                placeholder="news-url-slug"
                disabled={loading}
              />
              <p className="text-sm text-gray-500">
                This will be used in the URL. Example: "breaking-news-2024"
              </p>
            </div>

            {/* Author Section */}
            <div className="space-y-2">
              <label className="block font-medium">Author</label>
              <div className="relative">
                <button
                  type="button"
                  onClick={() => setShowAuthorDropdown(!showAuthorDropdown)}
                  disabled={loading}
                  className="w-full p-3 border border-gray-300 rounded-lg text-left flex items-center justify-between bg-white hover:bg-gray-50 disabled:bg-gray-100 disabled:cursor-not-allowed transition-all"
                >
                  <span className="flex items-center gap-2">
                    <Users size={18} className="text-gray-500" />
                    {getSelectedAuthorName()}
                  </span>
                  {form.author_id ? (
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleClearAuthor();
                      }}
                      className="text-gray-400 hover:text-gray-600"
                    >
                      <X size={18} />
                    </button>
                  ) : (
                    <ChevronRight size={18} className="text-gray-400" />
                  )}
                </button>

                {showAuthorDropdown && (
                  <div className="absolute z-30 mt-1 w-full bg-white border border-gray-200 rounded-lg shadow-xl max-h-60 overflow-y-auto">
                    <div className="py-2">
                      {authors.length > 0 ? (
                        authors.map((author) => (
                          <button
                            key={author.id}
                            type="button"
                            onClick={() => handleAuthorSelect(author.id)}
                            className={`w-full text-left px-4 py-3 hover:bg-gray-50 flex justify-between items-center border-b border-gray-100 last:border-b-0 ${
                              form.author_id == author.id ? 'bg-blue-50 text-blue-600' : ''
                            }`}
                          >
                            <div className="flex items-center gap-3">
                              {author.profile_image ? (
                                <img 
                                  src={author.profile_image} 
                                  alt={author.full_name}
                                  className="w-8 h-8 rounded-full object-cover border"
                                />
                              ) : (
                                <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
                                  <User size={16} className="text-gray-400" />
                                </div>
                              )}
                              <div className="text-left">
                                <div className="font-medium">{author.full_name}</div>
                                <div className="text-xs text-gray-500">{author.slug}</div>
                              </div>
                            </div>
                            <span className="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded">
                              {author.status || 'active'}
                            </span>
                          </button>
                        ))
                      ) : (
                        <div className="px-4 py-3 text-gray-500 text-sm">
                          No authors found. <a href="/admin/authors/add" className="text-[#0B6D76] hover:underline font-medium">Add authors first</a>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
              {form.author_id && (
                <div className="mt-2 p-3 bg-blue-50 rounded-lg">
                  <div className="flex justify-between items-center">
                    <span className="font-medium text-blue-700">Selected Author:</span>
                    <span className="text-blue-600">{getSelectedAuthorName()}</span>
                  </div>
                </div>
              )}
            </div>
          </div>
        );

      case 'CONTENT':
        return (
          <div className="space-y-6">
            <div className="space-y-2">
              <label className="block font-medium">
                News Content <span className="text-red-500">*</span>
              </label>
              <div className="border border-gray-300 rounded-lg overflow-hidden">
                <SummernoteEditor
                  value={form.description}
                  onChange={handleDescriptionChange}
                  placeholder="Write your news content here..."
                  height={400}
                />
              </div>
              {!form.description && (
                <p className="text-sm text-red-500">
                  News content is required
                </p>
              )}
            </div>

            <div className="space-y-2">
              <label className="block font-medium">Featured Image</label>
              <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-[#0B6D76] transition-all">
                <input
                  type="file"
                  accept="image/*"
                  onChange={handleImageChange}
                  className="hidden"
                  id="news-image-upload"
                  disabled={imageUploading || loading}
                />
                <label 
                  htmlFor="news-image-upload" 
                  className={`cursor-pointer flex flex-col items-center ${(imageUploading || loading) ? 'opacity-50 cursor-not-allowed' : ''}`}
                >
                  {form.image ? (
                    <div className="mb-4">
                      <img
                        src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${form.image}`}
                        alt="News preview"
                        className="max-w-full h-48 object-cover rounded-lg border shadow-md mx-auto"
                      />
                    </div>
                  ) : (
                    <div className="mb-4 p-4 bg-gray-100 rounded-full">
                      <svg className="w-12 h-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                      </svg>
                    </div>
                  )}
                  <span className="text-gray-700 font-medium">
                    {form.image ? 'Change Image' : 'Upload News Image'}
                  </span>
                  <span className="text-sm text-gray-500 mt-1">
                    Recommended: 1200x630px (JPG, PNG, or WebP)
                  </span>
                </label>
              </div>
              
              {form.image && (
                <div className="flex justify-between items-center mt-4 p-3 bg-gray-50 rounded-lg">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded overflow-hidden">
                      <img
                        src={`https://${process.env.NEXT_PUBLIC_AWS_BUCKET}.s3.${process.env.NEXT_PUBLIC_AWS_DEFAULT_REGION}.amazonaws.com/${form.image}`}
                        alt="Thumbnail"
                        className="w-full h-full object-cover"
                      />
                    </div>
                    <div>
                      <div className="font-medium text-sm">Image uploaded</div>
                      <div className="text-xs text-gray-500 truncate max-w-xs">{form.image.split('/').pop()}</div>
                    </div>
                  </div>
                  <button
                    type="button"
                    onClick={() => setForm(prev => ({ ...prev, image: '' }))}
                    className="text-red-500 hover:text-red-700 flex items-center gap-1 text-sm font-medium"
                    disabled={loading}
                  >
                    <Trash2 size={16} /> Remove
                  </button>
                </div>
              )}
              
              {imageUploading && (
                <div className="mt-3 p-3 bg-blue-50 rounded-lg flex items-center gap-3">
                  <Loader2 className="animate-spin text-[#0B6D76]" size={20} />
                  <div>
                    <div className="font-medium text-blue-700">Uploading image...</div>
                    <div className="text-sm text-blue-600">Please wait while we upload your image</div>
                  </div>
                </div>
              )}
            </div>
          </div>
        );
      
      case 'SCHEMA':
        return (
          <div className="space-y-6">
            <div className="flex justify-between items-center">
              <div>
                <h2 className="text-xl font-semibold text-gray-800">FAQ Schema Markup</h2>
                <p className="text-sm text-gray-600 mt-1">
                  Add FAQ questions and answers for better SEO and Google search results
                </p>
              </div>
              <button
                type="button"
                onClick={addSchemaRow}
                className="btn-primary flex items-center gap-2 px-4 py-2"
                disabled={loading}
              >
                <Plus size={18} /> Add FAQ Item
              </button>
            </div>

            {(() => {
              try {
                const questions = JSON.parse(form.sm_question);
                const answers = JSON.parse(form.sm_answer);
                return Array.isArray(questions) ? questions.map((question, index) => (
                  <div key={index} className="bg-gray-50 p-5 rounded-lg border border-gray-200">
                    <div className="flex justify-between items-center mb-3">
                      <div className="flex items-center gap-2">
                        <div className="w-8 h-8 rounded-full bg-blue-100 flex items-center justify-center">
                          <span className="text-blue-600 font-bold">{index + 1}</span>
                        </div>
                        <h3 className="font-medium text-gray-700">FAQ Item #{index + 1}</h3>
                      </div>
                      {questions.length > 1 && (
                        <button
                          type="button"
                          onClick={() => removeSchemaRow(index)}
                          className="text-red-500 hover:text-red-700 p-1"
                          title="Remove this FAQ item"
                          disabled={loading}
                        >
                          <Trash2 size={18} />
                        </button>
                      )}
                    </div>
                    <div className="space-y-4">
                      <div className="space-y-2">
                        <label className="block font-medium text-sm text-gray-700">Question</label>
                        <input
                          type="text"
                          value={safeString(question)}
                          onChange={(e) => handleSchemaChange(index, "question", e.target.value)}
                          placeholder="Enter your frequently asked question"
                          className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent transition-all"
                          disabled={loading}
                        />
                      </div>
                      <div className="space-y-2">
                        <label className="block font-medium text-sm text-gray-700">Answer</label>
                        <textarea
                          value={safeString(answers[index])}
                          onChange={(e) => handleSchemaChange(index, "answer", e.target.value)}
                          placeholder="Provide a detailed answer to the question"
                          className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent transition-all min-h-25"
                          disabled={loading}
                        />
                      </div>
                    </div>
                  </div>
                )) : [];
              } catch {
                return (
                  <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                    <div className="text-red-700 font-medium">Error loading FAQ data</div>
                    <p className="text-sm text-red-600 mt-1">Please reset the form or contact support</p>
                  </div>
                );
              }
            })()}
            
            {(() => {
              try {
                const questions = JSON.parse(form.sm_question);
                if (questions.length === 0 || (questions.length === 1 && !questions[0])) {
                  return (
                    <div className="text-center py-8 border-2 border-dashed border-gray-300 rounded-lg">
                      <svg className="w-12 h-12 text-gray-400 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                      </svg>
                      <h3 className="text-lg font-medium text-gray-700 mb-2">No FAQ Items Added</h3>
                      <p className="text-gray-500 mb-4">Add FAQ questions and answers to improve your news SEO</p>
                      <button
                        type="button"
                        onClick={addSchemaRow}
                        className="btn-primary px-4 py-2"
                        disabled={loading}
                      >
                        Add Your First FAQ
                      </button>
                    </div>
                  );
                }
              } catch {
                return null;
              }
            })()}
          </div>
        );

      case 'META TAGS':
        return (
          <div className="space-y-6">
            <div className="flex justify-between items-center">
              <div>
                <h2 className="text-xl font-semibold text-gray-800">Meta Tags & SEO</h2>
                <p className="text-sm text-gray-600 mt-1">
                  Customize how your news appears in search engines
                </p>
              </div>
              <label className="relative inline-flex items-center cursor-pointer">
                <input
                  type="checkbox"
                  name="enable_meta_tags"
                  checked={form.enable_meta_tags}
                  onChange={handleChange}
                  className="sr-only peer"
                  disabled={loading}
                />
                <div className="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-[#0B6D76]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:left-0.5 after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#0B6D76]"></div>
                <span className="ml-2 text-sm font-medium text-gray-700">
                  {form.enable_meta_tags ? 'Enabled' : 'Disabled'}
                </span>
              </label>
            </div>

            {form.enable_meta_tags && (
              <div className="space-y-6 mt-6">
                <div className="space-y-3">
                  <label className="block font-medium text-gray-800">
                    Meta Title
                    <span className="ml-2 text-xs font-normal text-gray-500">
                      (Appears in search results)
                    </span>
                  </label>
                  <input
                    type="text"
                    name="meta_title"
                    value={form.meta_title}
                    onChange={handleChange}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent transition-all"
                    placeholder="Enter meta title for search engines"
                    maxLength={60}
                    disabled={loading}
                  />
                  <div className="flex justify-between items-center">
                    <div className="text-xs text-gray-500">
                      Recommended: 50-60 characters
                    </div>
                    <div className={`text-xs font-medium ${
                      form.meta_title.length > 60 ? 'text-red-500' : 
                      form.meta_title.length >= 50 ? 'text-green-500' : 'text-yellow-500'
                    }`}>
                      {form.meta_title.length}/60 characters
                    </div>
                  </div>
                </div>

                <div className="space-y-3">
                  <label className="block font-medium text-gray-800">
                    Meta Description
                    <span className="ml-2 text-xs font-normal text-gray-500">
                      (Brief summary in search results)
                    </span>
                  </label>
                  <textarea
                    name="meta_description"
                    value={form.meta_description}
                    onChange={handleChange}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent transition-all min-h-25"
                    placeholder="Write a compelling meta description..."
                    maxLength={160}
                    disabled={loading}
                  />
                  <div className="flex justify-between items-center">
                    <div className="text-xs text-gray-500">
                      Recommended: 150-160 characters
                    </div>
                    <div className={`text-xs font-medium ${
                      form.meta_description.length > 160 ? 'text-red-500' : 
                      form.meta_description.length >= 150 ? 'text-green-500' : 'text-yellow-500'
                    }`}>
                      {form.meta_description.length}/160 characters
                    </div>
                  </div>
                </div>

                <div className="space-y-3">
                  <label className="block font-medium text-gray-800">
                    Meta Keywords
                    <span className="ml-2 text-xs font-normal text-gray-500">
                      (Separate with commas)
                    </span>
                  </label>
                  <input
                    type="text"
                    name="meta_keywords"
                    value={form.meta_keywords}
                    onChange={handleChange}
                    className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#0B6D76] focus:border-transparent transition-all"
                    placeholder="news, breaking, updates, industry, technology"
                    disabled={loading}
                  />
                  <div className="text-xs text-gray-500">
                    Example: breaking news, latest updates, industry news, technology
                  </div>
                </div>
              </div>
            )}

            {!form.enable_meta_tags && (
              <div className="bg-gray-50 border border-gray-200 rounded-lg p-6 text-center">
                <svg className="w-12 h-12 text-gray-400 mx-auto mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <h3 className="text-lg font-medium text-gray-700 mb-2">Meta Tags Disabled</h3>
                <p className="text-gray-500 mb-4 max-w-md mx-auto">
                  Enable meta tags to customize how this news appears in search engine results.
                  This can improve click-through rates and SEO performance.
                </p>
                <button
                  type="button"
                  onClick={() => setForm(prev => ({ ...prev, enable_meta_tags: true }))}
                  className="btn-primary px-4 py-2"
                  disabled={loading}
                >
                  Enable Meta Tags
                </button>
              </div>
            )}
          </div>
        );

      case 'SETTINGS':
        return (
          <div className="space-y-6">
            <div>
              <h2 className="text-xl font-semibold text-gray-800 mb-1">News Settings</h2>
              <p className="text-sm text-gray-600">
                Configure visibility and display options for this news
              </p>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="bg-white border border-gray-200 rounded-lg p-5">
                <div className="flex items-center gap-3 mb-4">
                  <div className="w-10 h-10 rounded-lg bg-blue-100 flex items-center justify-center">
                    <svg className="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                    </svg>
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-800">Active Status</h3>
                    <p className="text-sm text-gray-500">Show or hide this news</p>
                  </div>
                </div>
                <label className="flex items-center gap-3 cursor-pointer p-3 hover:bg-gray-50 rounded-lg transition-colors">
                  <div className="relative">
                    <input
                      type="checkbox"
                      name="is_active"
                      checked={form.is_active}
                      onChange={handleChange}
                      className="sr-only peer"
                      disabled={loading}
                    />
                    <div className="w-12 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-[#0B6D76]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:left-0.5 after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-green-500"></div>
                  </div>
                  <div className="flex-1">
                    <div className="font-medium text-gray-700">
                      {form.is_active ? 'News is Live' : 'News is Draft'}
                    </div>
                    <div className="text-sm text-gray-500">
                      {form.is_active 
                        ? 'This news is visible to the public' 
                        : 'This news is hidden from public view'}
                    </div>
                  </div>
                </label>
              </div>

              <div className="bg-white border border-gray-200 rounded-lg p-5">
                <div className="flex items-center gap-3 mb-4">
                  <div className="w-10 h-10 rounded-lg bg-yellow-100 flex items-center justify-center">
                    <Star className="w-5 h-5 text-yellow-600" fill="currentColor" />
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-800">Featured News</h3>
                    <p className="text-sm text-gray-500">Highlight on homepage</p>
                  </div>
                </div>
                <label className="flex items-center gap-3 cursor-pointer p-3 hover:bg-gray-50 rounded-lg transition-colors">
                  <div className="relative">
                    <input
                      type="checkbox"
                      name="is_featured"
                      checked={form.is_featured}
                      onChange={handleChange}
                      className="sr-only peer"
                      disabled={loading}
                    />
                    <div className="w-12 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-[#0B6D76]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:left-0.5 after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-yellow-500"></div>
                  </div>
                  <div className="flex-1">
                    <div className="font-medium text-gray-700">
                      {form.is_featured ? 'Featured' : 'Regular'}
                    </div>
                    <div className="text-sm text-gray-500">
                      {form.is_featured 
                        ? 'This news will be highlighted as featured' 
                        : 'This is a regular news item'}
                    </div>
                  </div>
                </label>
              </div>
            </div>

            <div className="bg-blue-50 border border-blue-200 rounded-lg p-5">
              <div className="flex items-start gap-3">
                <svg className="w-5 h-5 text-blue-500 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <div>
                  <h3 className="font-medium text-blue-700 mb-1">News Status Summary</h3>
                  <ul className="text-sm text-blue-600 space-y-1">
                    <li>• {form.is_active ? '✅ Live on website' : '📝 Draft mode (not visible to public)'}</li>
                    <li>• {form.is_featured ? '⭐ Featured on homepage' : '📄 Regular news listing'}</li>
                    <li>• {form.enable_meta_tags ? '🔍 SEO optimized' : '⚠️ Basic SEO (no custom meta tags)'}</li>
                    <li>• {form.author_id ? '👤 Author assigned' : '👥 No author assigned'}</li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        );

      default:
        return null;
    }
  };

  return (
    <form onSubmit={handleSubmit} className="min-h-screen flex flex-col md:flex-row bg-gray-50">
      {/* Mobile Menu Button */}
      <div className="md:hidden bg-white p-4 flex justify-between items-center border-b shadow-sm">
        <div>
          <h2 className="text-xl font-bold text-gray-800">
            {isEditMode ? 'Edit News' : 'Create News'}
          </h2>
          <p className="text-sm text-gray-500">
            {isEditMode ? 'Update existing news' : 'Add new news to your website'}
          </p>
        </div>
        <button
          type="button"
          onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
          className="text-gray-500 hover:text-gray-700 p-2 rounded-lg hover:bg-gray-100 transition-colors"
        >
          <svg className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            {mobileMenuOpen ? (
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            ) : (
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
            )}
          </svg>
        </button>
      </div>

      {/* Mobile Sidebar */}
      {mobileMenuOpen && (
        <div className="md:hidden bg-white border-b shadow-lg p-4">
          <ul className="space-y-2">
            {tabs.map((tab) => (
              <li key={tab}>
                <button
                  type="button"
                  onClick={() => {
                    setActiveTab(tab);
                    setMobileMenuOpen(false);
                  }}
                  className={`w-full text-left px-4 py-3 rounded-lg transition-all flex items-center justify-between ${
                    activeTab === tab 
                      ? 'bg-linear-to-r from-[#0B6D76] to-[#094F56] text-white shadow-md' 
                      : 'hover:bg-gray-100 text-gray-700'
                  }`}
                >
                  <span>{tab}</span>
                  {activeTab === tab && (
                    <div className="w-2 h-2 rounded-full bg-white"></div>
                  )}
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}

      {/* Desktop Sidebar */}
      <div className="hidden md:block w-64 bg-white border-r shadow-sm p-6">
        <div className="mb-8">
          <h2 className="text-2xl font-bold text-gray-800 mb-2">
            {isEditMode ? 'Edit News' : 'Create News'}
          </h2>
          <p className="text-sm text-gray-500">
            {isEditMode 
              ? 'Update and manage your news content' 
              : 'Add fresh content to keep your audience informed'}
          </p>
        </div>
        <ul className="space-y-2">
          {tabs.map((tab) => (
            <li key={tab}>
              <button
                type="button"
                onClick={() => setActiveTab(tab)}
                className={`w-full text-left px-4 py-3 rounded-xl transition-all flex items-center justify-between group ${
                  activeTab === tab 
                    ? 'bg-linear-to-r from-[#0B6D76] to-[#094F56] text-white shadow-lg transform translate-x-1' 
                    : 'hover:bg-gray-100 text-gray-700 hover:text-gray-900'
                }`}
              >
                <div className="flex items-center gap-3">
                  <div className={`w-2 h-2 rounded-full transition-colors ${
                    activeTab === tab ? 'bg-white' : 'bg-gray-300 group-hover:bg-[#0B6D76]'
                  }`}></div>
                  <span className="font-medium">{tab}</span>
                </div>
                {activeTab === tab && (
                  <ChevronRight size={18} className="text-white" />
                )}
              </button>
            </li>
          ))}
        </ul>
        
        <div className="mt-8 pt-6 border-t border-gray-200">
          <div className="text-sm text-gray-500 mb-2">Progress</div>
          <div className="w-full bg-gray-200 rounded-full h-2">
            <div 
              className="bg-linear-to-r from-[#0B6D76] to-[#094F56] h-2 rounded-full transition-all duration-500"
              style={{ width: `${(tabs.indexOf(activeTab) + 1) * 20}%` }}
            ></div>
          </div>
          <div className="flex justify-between mt-2 text-sm">
            <span className="text-gray-700">{activeTab}</span>
            <span className="font-medium text-[#0B6D76]">
              {tabs.indexOf(activeTab) + 1} of {tabs.length}
            </span>
          </div>
        </div>
      </div>

      {/* Main Content */}
      <div className="flex-1 p-4 md:p-6 lg:p-8">
        <div className="max-w-4xl mx-auto">
          {/* Mobile Tab Indicator */}
          <div className="md:hidden mb-6">
            <div className="bg-linear-to-r from-[#0B6D76] to-[#094F56] text-white px-4 py-3 rounded-xl shadow-md flex items-center justify-between">
              <span className="font-bold">{activeTab}</span>
              <div className="text-sm bg-white/20 px-3 py-1 rounded-full">
                {tabs.indexOf(activeTab) + 1} / {tabs.length}
              </div>
            </div>
          </div>

          <div className="bg-white p-4 sm:p-6 lg:p-8 rounded-xl border border-gray-200 shadow-sm mb-6">
            {renderContent()}
          </div>

          {/* Navigation buttons */}
          <div className="flex justify-between items-center pt-6 border-t border-gray-200">
            {activeTab !== 'BASIC INFO' ? (
              <button
                type="button"
                onClick={() => setActiveTab(tabs[tabs.indexOf(activeTab) - 1])}
                className="btn-gray flex items-center gap-2 px-5 py-3 rounded-lg"
                disabled={loading}
              >
                <ChevronLeft size={18} /> Previous
              </button>
            ) : (
              <div></div>
            )}

            {activeTab !== 'SETTINGS' ? (
              <button
                type="button"
                onClick={() => setActiveTab(tabs[tabs.indexOf(activeTab) + 1])}
                className="btn-primary flex items-center gap-2 px-5 py-3 rounded-lg"
                disabled={loading}
              >
                Next <ChevronRight size={18} />
              </button>
            ) : (
              <button
                type="submit"
                className="btn-primary flex items-center gap-2 px-6 py-3 rounded-lg shadow-md hover:shadow-lg transition-all"
                disabled={loading}
              >
                {loading ? (
                  <>
                    <Loader2 className="animate-spin" size={18} /> 
                    {isEditMode ? 'Updating News...' : 'Creating News...'}
                  </>
                ) : (
                  <>
                    <Save size={18} /> 
                    {isEditMode ? 'Update News' : 'Publish News'}
                  </>
                )}
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Close dropdowns when clicking outside */}
      {showAuthorDropdown && (
        <div
          className="fixed inset-0 z-20"
          onClick={() => setShowAuthorDropdown(false)}
        />
      )}

      <style jsx>{`
        .btn-primary {
          @apply bg-linear-to-b from-[#0B6D76] to-[#094F56] text-white font-semibold transition-all hover:from-[#094F56] hover:to-[#083a40] hover:shadow-md disabled:opacity-70 disabled:cursor-not-allowed;
        }
        .btn-gray {
          @apply bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold transition-colors disabled:opacity-50 disabled:cursor-not-allowed;
        }
      `}</style>
    </form>
  );
}