'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="text-primary h-6 w-6 animate-spin" />
      </div>
    )
  }

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

      <div className="border-border border-b px-4 py-3">
        <div className="flex items-center justify-between">
          <button
            onClick={() => onNavigate?.('/pages')}
            className="text-muted-foreground hover:text-foreground inline-flex items-center gap-2 text-sm transition-colors"
          >
            <ArrowLeft className="h-4 w-4" />
            Back to Pages
          </button>
          <div className="flex items-center gap-3">
            <button className="border-border hover:bg-muted flex items-center gap-2 rounded-lg border px-3 py-1.5 text-sm transition-colors">
              <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="placeholder:text-muted-foreground mb-4 w-full border-none px-0 text-2xl font-medium focus:ring-0 focus:outline-none sm:text-3xl"
            />

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

            <div className="border-border rounded-lg border-2 border-dashed p-8 text-center">
              <p className="text-muted-foreground mb-2">No blocks added yet</p>
              <p className="text-muted-foreground text-sm">
                Click "Add Block" to start building your page
              </p>
              <button className="bg-primary text-primary-foreground hover:bg-primary/90 mt-4 rounded-lg px-4 py-2 text-sm transition-colors">
                Add Block
              </button>
            </div>
          </div>
        </div>

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

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