import { useState, useEffect } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { posts as postsAPI, categories as categoriesAPI, media as mediaAPI } from '../../utils/api'
import BlockEditor from '../components/BlockEditor'
import SEOPanel from '../components/SEOPanel'
import BannerUpload from '../components/BannerUpload'
import { Save, Send, Clock } from 'lucide-react'

export default function AdminPostEditor() {
  const { id } = useParams()
  const navigate = useNavigate()
  const [categories, setCategories] = useState([])
  const [formData, setFormData] = useState({
    title: '',
    excerpt: '',
    category_id: '',
    content: [],
    banner_image: '',
    thumbnail_image: '',
    seo_title: '',
    seo_description: '',
    seo_keywords: '',
    og_image: '',
    status: 'draft',
  })
  const [loading, setLoading] = useState(!!id)
  const [saving, setSaving] = useState(false)
  const [scheduledAt, setScheduledAt] = useState('')

  useEffect(() => {
    const fetchData = async () => {
      try {
        const catsRes = await categoriesAPI.getAll()
        setCategories(catsRes.data)

        if (id) {
          const postRes = await postsAPI.getByIdAdmin(id)
          setFormData(postRes.data)
          if (postRes.data.scheduled_at) {
            setScheduledAt(postRes.data.scheduled_at.split('T')[0])
          }
        }
      } catch (err) {
        console.error('Failed to fetch data:', err)
      } finally {
        setLoading(false)
      }
    }
    fetchData()
  }, [id])

  const handleSave = async (status) => {
    if (!formData.title || !formData.category_id) {
      alert('Title and category are required')
      return
    }

    setSaving(true)
    try {
      const data = {
        ...formData,
        status,
        scheduled_at: status === 'scheduled' ? scheduledAt : null,
      }

      if (id) {
        await postsAPI.update(id, data)
      } else {
        await postsAPI.create(data)
      }

      alert(`Post ${status} successfully!`)
      navigate('/admin/posts')
    } catch (err) {
      alert('Error: ' + err.response?.data?.error || err.message)
    } finally {
      setSaving(false)
    }
  }

  const handlePublish = async () => {
    if (!id) {
      alert('Save draft first before publishing')
      return
    }

    setSaving(true)
    try {
      await postsAPI.publish(id)
      alert('Post published successfully!')
      navigate('/admin/posts')
    } catch (err) {
      alert('Error: ' + err.response?.data?.error || err.message)
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
      </div>
    )
  }

  return (
    <div className="p-8">
      <div className="max-w-6xl mx-auto">
        {/* Header */}
        <div className="mb-8 flex justify-between items-center">
          <h1 className="text-4xl font-bold text-gray-900">
            {id ? 'Edit Post' : 'Create New Post'}
          </h1>
          <div className="flex gap-3">
            <button
              onClick={() => handleSave('draft')}
              disabled={saving}
              className="flex items-center gap-2 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 disabled:bg-gray-400 transition"
            >
              <Save size={18} /> Save Draft
            </button>
            {id && (
              <button
                onClick={handlePublish}
                disabled={saving}
                className="flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:bg-gray-400 transition"
              >
                <Send size={18} /> Publish
              </button>
            )}
          </div>
        </div>

        <div className="grid lg:grid-cols-3 gap-8">
          {/* Main Editor */}
          <div className="lg:col-span-2 space-y-6">
            {/* Title */}
            <div className="bg-white rounded-lg p-6 shadow-md">
              <label className="block text-sm font-semibold text-gray-900 mb-2">
                Post Title *
              </label>
              <input
                type="text"
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                placeholder="Enter post title"
              />
            </div>

            {/* Category */}
            <div className="bg-white rounded-lg p-6 shadow-md">
              <label className="block text-sm font-semibold text-gray-900 mb-2">
                Category *
              </label>
              <select
                value={formData.category_id}
                onChange={(e) => setFormData({ ...formData, category_id: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              >
                <option value="">Select a category</option>
                {categories.map(cat => (
                  <option key={cat.id} value={cat.id}>{cat.name}</option>
                ))}
              </select>
            </div>

            {/* Excerpt */}
            <div className="bg-white rounded-lg p-6 shadow-md">
              <label className="block text-sm font-semibold text-gray-900 mb-2">
                Excerpt
              </label>
              <textarea
                value={formData.excerpt}
                onChange={(e) => setFormData({ ...formData, excerpt: e.target.value })}
                rows="3"
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
                placeholder="Brief description (used in previews)"
              />
            </div>

            {/* Banner Image */}
            <BannerUpload
              value={formData.banner_image}
              onChange={(val) => setFormData({ ...formData, banner_image: val })}
              label="Banner Image"
            />

            {/* Thumbnail */}
            <BannerUpload
              value={formData.thumbnail_image}
              onChange={(val) => setFormData({ ...formData, thumbnail_image: val })}
              label="Thumbnail Image"
            />

            {/* Content Blocks */}
            <BlockEditor
              blocks={formData.content}
              onChange={(blocks) => setFormData({ ...formData, content: blocks })}
            />
          </div>

          {/* Sidebar */}
          <div className="space-y-6">
            {/* Status */}
            <div className="bg-white rounded-lg p-6 shadow-md">
              <label className="block text-sm font-semibold text-gray-900 mb-2">
                Status
              </label>
              <select
                value={formData.status}
                onChange={(e) => setFormData({ ...formData, status: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"
              >
                <option value="draft">Draft</option>
                <option value="published">Published</option>
                <option value="scheduled">Scheduled</option>
              </select>
            </div>

            {/* Scheduled Date */}
            {formData.status === 'scheduled' && (
              <div className="bg-white rounded-lg p-6 shadow-md">
                <label className="block text-sm font-semibold text-gray-900 mb-2">
                  <Clock size={18} className="inline mr-2" />
                  Schedule Date
                </label>
                <input
                  type="date"
                  value={scheduledAt}
                  onChange={(e) => setScheduledAt(e.target.value)}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg"
                />
              </div>
            )}

            {/* SEO Panel */}
            <SEOPanel formData={formData} setFormData={setFormData} />
          </div>
        </div>
      </div>
    </div>
  )
}
