"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import dynamic from "next/dynamic"
import { ArrowLeft, Save, Loader2, Code, Eye } from "lucide-react"
import Swal from "sweetalert2";

const BlockEditor = dynamic(() => import("@/components/admin/BlockEditor"), { ssr: false })

export default function NewPage() {
  const router = useRouter()
  const [saving, setSaving] = useState(false)
  
  const [title, setTitle] = useState("")
  const [slug, setSlug] = useState("")
  const [content, setContent] = useState("")
  const [published, setPublished] = useState(true)
  const [editorMode, setEditorMode] = useState<"visual" | "code">("visual")

  // Auto-generate slug from title
  const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newTitle = e.target.value
    setTitle(newTitle)
    setSlug(newTitle.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''))
  }

  const handleSave = async (e: React.FormEvent) => {
    e.preventDefault()
    setSaving(true)
    
    try {
      const res = await fetch("/api/admin/pages", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ title, slug, content, published })
      })
      
      const data = await res.json()
      
      if (!res.ok) throw new Error(data.message)
      
      Swal.fire({ text: "Page created successfully!", confirmButtonColor: "#18181b", icon: "success" })
      router.push("/admin/pages")
      router.refresh()
    } catch (err: any) {
      Swal.fire({ text: err.message || "Failed to create page", confirmButtonColor: "#18181b", icon: "error" })
    } finally {
      setSaving(false)
    }
  }

  return (
    <div className="max-w-4xl space-y-6 pb-20">
      <div className="flex items-center gap-4">
        <Link href="/admin/pages" className="p-2 border border-zinc-200 rounded-sm hover:bg-zinc-50 transition-colors">
          <ArrowLeft className="w-4 h-4" />
        </Link>
        <div>
          <h1 className="text-2xl font-black uppercase tracking-tight text-zinc-950">Create New Page</h1>
          <p className="text-sm text-zinc-500 mt-1">Add a new dynamic page to your store.</p>
        </div>
      </div>

      <form onSubmit={handleSave} className="bg-white border border-zinc-200 rounded-lg p-6 space-y-8">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="space-y-2">
            <label className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 block">Page Title</label>
            <input 
              type="text" 
              required
              value={title}
              onChange={handleTitleChange}
              placeholder="e.g. Privacy Policy"
              className="w-full px-4 py-3 text-sm border border-zinc-200 bg-zinc-50 focus:bg-white focus:outline-none focus:border-zinc-950 transition-all"
            />
          </div>
          <div className="space-y-2">
            <label className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 block">URL Slug</label>
            <div className="flex items-center border border-zinc-200 bg-zinc-50 focus-within:bg-white focus-within:border-zinc-950 transition-all">
              <span className="px-3 text-zinc-400 text-sm">/pages/</span>
              <input 
                type="text" 
                required
                value={slug}
                onChange={(e) => setSlug(e.target.value)}
                placeholder="privacy-policy"
                className="w-full py-3 pr-4 text-sm bg-transparent outline-none"
              />
            </div>
          </div>
        </div>

        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <label className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 flex items-center gap-2">
              <Code className="w-3 h-3" /> Page Content
            </label>
            <div className="flex items-center gap-2 bg-zinc-100 p-1 rounded-md">
              <button
                type="button"
                onClick={() => setEditorMode("visual")}
                className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold rounded-sm transition-all ${
                  editorMode === "visual" ? "bg-white shadow-sm text-zinc-900" : "text-zinc-500 hover:text-zinc-700"
                }`}
              >
                <Eye className="w-3 h-3" /> Visual
              </button>
              <button
                type="button"
                onClick={() => setEditorMode("code")}
                className={`flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold rounded-sm transition-all ${
                  editorMode === "code" ? "bg-white shadow-sm text-zinc-900" : "text-zinc-500 hover:text-zinc-700"
                }`}
              >
                <Code className="w-3 h-3" /> HTML / Code
              </button>
            </div>
          </div>
          <div className="focus-within:ring-2 ring-zinc-950 transition-all rounded-lg overflow-hidden border border-zinc-200">
            {editorMode === "visual" ? (
              <div className="p-4 bg-white min-h-[400px]">
                <BlockEditor 
                  initialContent={content} 
                  onChange={setContent} 
                />
              </div>
            ) : (
              <textarea
                value={content}
                onChange={(e) => setContent(e.target.value)}
                placeholder="<h1>Hello World</h1>"
                className="w-full min-h-[400px] p-4 font-mono text-sm bg-zinc-50 outline-none resize-y"
              />
            )}
          </div>
        </div>

        <div className="flex items-center justify-between pt-8 border-t border-zinc-100">
          <div className="flex items-center gap-3">
            <label className="relative inline-flex items-center cursor-pointer">
              <input 
                type="checkbox" 
                className="sr-only peer" 
                checked={published}
                onChange={(e) => setPublished(e.target.checked)}
              />
              <div className="w-11 h-6 bg-zinc-200 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-zinc-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-zinc-950"></div>
            </label>
            <div>
              <span className="text-sm font-bold text-zinc-800 block">Published</span>
              <span className="text-[10px] text-zinc-500 uppercase tracking-widest">Make visible to public</span>
            </div>
          </div>

          <button 
            type="submit" 
            disabled={saving}
            className="flex items-center gap-2 rounded-sm bg-zinc-950 px-8 py-3 text-xs font-bold uppercase tracking-widest text-white hover:bg-zinc-800 disabled:opacity-50 transition-colors"
          >
            {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
            {saving ? "Saving..." : "Save Page"}
          </button>
        </div>
      </form>
    </div>
  )
}
