'use client'

import { useState, useTransition } from 'react'
import { useRouter } from 'next/navigation'

interface BlogPost {
  id: number
  titleTr: string
  titleEn: string | null
  slug: string
  contentTr: string
  contentEn: string | null
  excerpt: string | null
  coverImage: string | null
  isPublished: boolean
}

export default function AdminBlogForm({ post }: { post?: BlogPost }) {
  const router = useRouter()
  const [pending, start] = useTransition()
  const [error, setError] = useState('')
  const [form, setForm] = useState({
    titleTr: post?.titleTr ?? '',
    titleEn: post?.titleEn ?? '',
    slug: post?.slug ?? '',
    contentTr: post?.contentTr ?? '',
    contentEn: post?.contentEn ?? '',
    excerpt: post?.excerpt ?? '',
    coverImage: post?.coverImage ?? '',
    isPublished: post?.isPublished ?? false,
  })

  function slugify(str: string) {
    return str
      .toLowerCase()
      .replace(/ğ/g, 'g').replace(/ü/g, 'u').replace(/ş/g, 's')
      .replace(/ı/g, 'i').replace(/ö/g, 'o').replace(/ç/g, 'c')
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)/g, '')
  }

  function set(key: string, val: string | boolean) {
    setForm(f => ({ ...f, [key]: val }))
  }

  function handleTitleTr(val: string) {
    setForm(f => ({ ...f, titleTr: val, slug: post ? f.slug : slugify(val) }))
  }

  async function handleUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return
    const fd = new FormData()
    fd.append('file', file)
    const res = await fetch('/api/admin/upload', { method: 'POST', body: fd })
    if (res.ok) {
      const { url } = await res.json()
      set('coverImage', url)
    }
  }

  function submit() {
    start(async () => {
      setError('')
      const url = post ? `/api/admin/blog/${post.id}` : '/api/admin/blog'
      const method = post ? 'PATCH' : 'POST'
      const res = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      })
      if (res.ok) {
        router.push('/admin/blog')
        router.refresh()
      } else {
        const d = await res.json()
        setError(d.error ?? 'Bir hata oluştu')
      }
    })
  }

  const ic = 'w-full px-3 py-2 rounded-lg border border-sand bg-cream font-body text-sm focus:outline-none focus:border-earth transition-colors'
  const lb = 'block font-body text-xs text-brown/50 tracking-widest uppercase mb-1'

  return (
    <div className="space-y-5">
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div>
          <label className={lb}>Başlık (TR) *</label>
          <input type="text" required value={form.titleTr}
            onChange={e => handleTitleTr(e.target.value)}
            className={ic} />
        </div>
        <div>
          <label className={lb}>Başlık (EN)</label>
          <input type="text" value={form.titleEn}
            onChange={e => set('titleEn', e.target.value)}
            className={ic} />
        </div>
      </div>

      <div>
        <label className={lb}>Slug *</label>
        <input type="text" required value={form.slug}
          onChange={e => set('slug', e.target.value)}
          className={`${ic} font-mono`} />
        <p className="font-body text-xs text-brown/40 mt-1">Başlıktan otomatik üretilir, değiştirebilirsiniz.</p>
      </div>

      <div>
        <label className={lb}>Özet</label>
        <textarea rows={2} value={form.excerpt}
          onChange={e => set('excerpt', e.target.value)}
          className={`${ic} resize-none`} />
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div>
          <label className={lb}>İçerik (TR) *</label>
          <textarea rows={12} required value={form.contentTr}
            onChange={e => set('contentTr', e.target.value)}
            className={`${ic} resize-y`} />
        </div>
        <div>
          <label className={lb}>İçerik (EN)</label>
          <textarea rows={12} value={form.contentEn}
            onChange={e => set('contentEn', e.target.value)}
            className={`${ic} resize-y`} />
        </div>
      </div>

      <div>
        <label className={lb}>Kapak Görseli</label>
        <input type="file" accept="image/*" onChange={handleUpload}
          className="block font-body text-sm text-brown/60 file:mr-3 file:py-1.5 file:px-4 file:rounded-lg file:border file:border-earth file:bg-transparent file:font-body file:text-xs file:text-earth file:tracking-widest file:uppercase file:cursor-pointer" />
        {form.coverImage && (
          <img src={form.coverImage} alt="" className="mt-2 h-32 w-auto object-cover rounded-lg" />
        )}
      </div>

      <div className="flex items-center gap-3">
        <button type="button"
          onClick={() => set('isPublished', !form.isPublished)}
          className={`relative inline-flex h-5 w-10 items-center rounded-full transition-colors ${form.isPublished ? 'bg-green-500' : 'bg-gray-300'}`}>
          <span className={`inline-block h-4 w-4 rounded-full bg-white shadow transition-transform ${form.isPublished ? 'translate-x-5' : 'translate-x-0.5'}`} />
        </button>
        <span className="font-body text-sm text-brown">{form.isPublished ? 'Yayında' : 'Taslak'}</span>
      </div>

      {error && <p className="font-body text-sm text-red-600 bg-red-50 rounded-lg px-4 py-2">{error}</p>}

      <div className="flex items-center gap-3 pt-2">
        <button onClick={submit} disabled={pending}
          className="px-8 py-2 rounded-lg bg-brown text-cream font-body text-sm tracking-widest uppercase hover:bg-earth transition-colors disabled:opacity-60">
          {pending ? 'Kaydediliyor...' : (post ? 'Güncelle' : 'Kaydet')}
        </button>
        <button type="button" onClick={() => router.push('/admin/blog')}
          className="px-6 py-2 rounded-lg border border-sand font-body text-sm text-brown/60 hover:border-earth transition-colors">
          İptal
        </button>
      </div>
    </div>
  )
}
