'use client'

import { useState, useEffect } from 'react'
import { ArrowLeft, Eye, Loader2, AlertTriangle } from 'lucide-react'
import { toast } from 'sonner'
import { SEOPanel, type SEOData } from '../components/SEOPanel.js'
import { useApiData } from '../lib/useApiData.js'
import { cmsApi } from '../lib/api.js'

export interface PageEditorProps {
  id?: string
  onNavigate?: (path: string) => void
}

export function PageEditor({ id, onNavigate }: PageEditorProps) {
  const isNew = !id
  const { data, loading, error } = useApiData<any>(isNew ? '' : `/collections/pages/${id}`)

  const [title, setTitle] = useState('')
  const [slug, setSlug] = useState('')
  const [status, setStatus] = useState<'draft' | 'published'>('draft')
  const [saving, setSaving] = useState(false)
  const [initialized, setInitialized] = useState(isNew)
  const [seoData, setSeoData] = useState<SEOData>({})

  useEffect(() => {
    if (data && !initialized) {
      setTitle(data.title ?? '')
      setSlug(data.slug ?? '')
      setStatus(data.status === 'PUBLISHED' ? 'published' : 'draft')
      setInitialized(true)
    }
  }, [data, initialized])

  const savePage = async () => {
    setSaving(true)
    const body = JSON.stringify({
      title,
      slug,
      status: status === 'published' ? 'PUBLISHED' : 'DRAFT',
    })

    const res = isNew
      ? await cmsApi('/collections/pages', { method: 'POST', body })
      : await cmsApi(`/collections/pages/${id}`, { method: 'PUT', body })

    setSaving(false)
    if (res.error) {
      toast.error(res.error)
    } else {
      toast.success('Page saved successfully!')
      if (isNew && (res.data as any)?.id) {
        onNavigate?.(`/pages/${(res.data as any).id}`)
      }
    }
  }

  const publishPage = async () => {
    setSaving(true)
    const body = JSON.stringify({
      title,
      slug,
      status: 'PUBLISHED',
    })

    const endpoint = isNew ? '/collections/pages' : `/collections/pages/${id}`
    const method = isNew ? 'POST' : 'PUT'
    const res = await cmsApi(endpoint, { method, body })

    setSaving(false)
    if (res.error) {
      toast.error(res.error)
    } else {
      setStatus('published')
      toast.success('Page published!')
      if (isNew && (res.data as any)?.id) {
        onNavigate?.(`/pages/${(res.data as any).id}`)
      }
    }
  }

  if (!isNew && loading) {
    return (
      <div className="flex h-full items-center justify-center">
        <Loader2 className="h-6 w-6 animate-spin text-blue-600" />
      </div>
    )
  }

  return (
    <div className="flex h-full flex-col bg-white">
      {error && (
        <div className="mx-4 mt-3 flex items-center gap-3 rounded-lg border border-red-200 bg-red-50 p-3">
          <AlertTriangle className="h-5 w-5 shrink-0 text-red-600" />
          <span className="flex-1 text-sm text-red-800">{error}</span>
        </div>
      )}

      <div className="border-b border-gray-200 px-4 py-3">
        <div className="flex items-center justify-between">
          <button
            onClick={() => onNavigate?.('/pages')}
            className="inline-flex items-center gap-2 text-sm text-gray-600 transition-colors hover:text-gray-900"
          >
            <ArrowLeft className="h-4 w-4" />
            Back to Pages
          </button>
          <div className="flex items-center gap-3">
            <button className="flex items-center gap-2 rounded-lg border border-gray-300 px-3 py-1.5 text-sm transition-colors hover:bg-gray-50">
              <Eye className="h-4 w-4" />
              Preview
            </button>
          </div>
        </div>
      </div>

      <div className="flex flex-1 overflow-hidden">
        <div className="flex-1 overflow-y-auto">
          <div className="mx-auto max-w-4xl p-3 pr-6 sm:p-4 sm:pr-8">
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Page title"
              className="mb-4 w-full border-none px-0 text-2xl font-bold placeholder:text-gray-300 focus:ring-0 focus:outline-none sm:text-3xl"
            />

            <div className="mb-4">
              <label className="mb-1 block text-xs font-medium text-gray-600">URL Slug</label>
              <input
                type="text"
                value={slug}
                onChange={(e) => setSlug(e.target.value)}
                placeholder="url-slug"
                className="w-full rounded-lg border border-gray-300 px-3 py-1.5 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
              />
            </div>

            <div className="rounded-lg border-2 border-dashed border-gray-300 p-8 text-center">
              <p className="mb-2 text-gray-500">No blocks added yet</p>
              <p className="text-sm text-gray-400">Click "Add Block" to start building your page</p>
              <button className="mt-4 rounded-lg bg-blue-600 px-4 py-2 text-sm text-white transition-colors hover:bg-blue-700">
                Add Block
              </button>
            </div>
          </div>
        </div>

        <div className="w-[30%] overflow-y-auto border-l border-gray-200 bg-gray-50">
          <div className="space-y-4 p-4">
            <div className="rounded-lg border border-gray-200 bg-white p-4">
              <h3 className="mb-3 text-sm font-semibold text-gray-900">Publish</h3>
              <div className="space-y-3">
                <div>
                  <label className="mb-1 block text-xs font-medium text-gray-700">Status</label>
                  <select
                    value={status}
                    onChange={(e) => setStatus(e.target.value as 'draft' | 'published')}
                    className="w-full rounded-lg border border-gray-300 px-3 py-1.5 text-sm focus:ring-2 focus:ring-blue-500 focus:outline-none"
                  >
                    <option value="draft">Draft</option>
                    <option value="published">Published</option>
                  </select>
                </div>
                <button
                  onClick={savePage}
                  disabled={saving}
                  className="w-full rounded-lg bg-blue-600 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700 disabled:opacity-50"
                >
                  {saving ? 'Saving...' : 'Save Page'}
                </button>
                {status === 'draft' && (
                  <button
                    onClick={publishPage}
                    disabled={saving}
                    className="w-full rounded-lg bg-green-600 py-2 text-sm font-medium text-white transition-colors hover:bg-green-700 disabled:opacity-50"
                  >
                    {saving ? 'Publishing...' : 'Publish'}
                  </button>
                )}
              </div>
            </div>

            <SEOPanel title={title} slug={slug} seoData={seoData} onChange={setSeoData} />
          </div>
        </div>
      </div>
    </div>
  )
}
