'use client'

import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { createOrUpdateBlogPostAction } from '@/app/actions'
import { Link } from '@/i18n/routing'
import { ArrowLeft, Save } from 'lucide-react'

interface FormProps {
  post: any | null
}

export default function BlogPostForm({ post }: FormProps) {
  const router = useRouter()
  const [activeTab, setActiveTab] = useState<'tr' | 'en' | 'ru'>('tr')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setLoading(true)
    setError('')
    setSuccess(false)

    const formData = new FormData(e.currentTarget)
    if (post) {
      formData.append('id', post.id)
    }

    try {
      const res = await createOrUpdateBlogPostAction(formData)
      if (res.error) {
        setError(res.error)
      } else {
        setSuccess(true)
        setTimeout(() => {
          router.push('/admin/blog')
          router.refresh()
        }, 1500)
      }
    } catch (err) {
      setError('İşlem sırasında bir hata oluştu.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {error && (
        <div className="bg-bougainvillea/10 border border-bougainvillea/25 text-bougainvillea p-4 rounded-xl text-xs font-semibold">
          {error}
        </div>
      )}

      {success && (
        <div className="bg-turquoise/10 border border-turquoise/25 text-turquoise p-4 rounded-xl text-xs font-bold">
          Yazı başarıyla kaydedildi! Yönlendiriliyorsunuz...
        </div>
      )}

      <div className="border-b border-pine/8">
        <div className="flex gap-2">
          {(['tr', 'en', 'ru'] as const).map((lang) => {
            const label = lang === 'tr' ? '🇹🇷 Türkçe' : lang === 'en' ? '🇬🇧 English' : '🇷🇺 Русский'
            const isTabActive = activeTab === lang
            return (
              <button
                key={lang}
                type="button"
                onClick={() => setActiveTab(lang)}
                className={`py-3 px-4 font-heading font-bold text-xs border-b-2 transition lowercase ${
                  isTabActive
                    ? 'border-turquoise text-turquoise'
                    : 'border-transparent text-shutter hover:text-pine'
                }`}
              >
                {label}
              </button>
            )
          })}
        </div>
      </div>

      <div className="space-y-4">
        {activeTab === 'tr' && (
          <div className="space-y-4">
            <div className="space-y-1.5">
              <label className="block text-xs font-mono uppercase tracking-wider text-shutter">Başlık (TR) *</label>
              <input type="text" name="titleTr" required defaultValue={post?.titleTr || ''} className="w-full bg-stone border border-pine/10 rounded-xl px-4 py-3 text-sm focus:ring-1 focus:ring-turquoise outline-none text-ink" placeholder="Örn: Marmaris'in En İyi 5 Plajı" />
            </div>
            <div className="space-y-1.5">
              <label className="block text-xs font-mono uppercase tracking-wider text-shutter">İçerik (TR) *</label>
              <textarea name="contentTr" required rows={10} defaultValue={post?.contentTr || ''} className="w-full bg-stone border border-pine/10 rounded-xl px-4 py-3 text-sm focus:ring-1 focus:ring-turquoise outline-none text-ink" placeholder="Yazı içeriği..." />
            </div>
          </div>
        )}
        {activeTab === 'en' && (
          <div className="space-y-4">
            <div className="space-y-1.5">
              <label className="block text-xs font-mono uppercase tracking-wider text-shutter">Başlık (EN) *</label>
              <input type="text" name="titleEn" required defaultValue={post?.titleEn || ''} className="w-full bg-stone border border-pine/10 rounded-xl px-4 py-3 text-sm focus:ring-1 focus:ring-turquoise outline-none text-ink" placeholder="e.g. Top 5 Beaches in Marmaris" />
            </div>
            <div className="space-y-1.5">
              <label className="block text-xs font-mono uppercase tracking-wider text-shutter">İçerik (EN) *</label>
              <textarea name="contentEn" required rows={10} defaultValue={post?.contentEn || ''} className="w-full bg-stone border border-pine/10 rounded-xl px-4 py-3 text-sm focus:ring-1 focus:ring-turquoise outline-none text-ink" placeholder="Post content..." />
            </div>
          </div>
        )}
        {activeTab === 'ru' && (
          <div className="space-y-4">
            <div className="space-y-1.5">
              <label className="block text-xs font-mono uppercase tracking-wider text-shutter">Başlık (RU) *</label>
              <input type="text" name="titleRu" required defaultValue={post?.titleRu || ''} className="w-full bg-stone border border-pine/10 rounded-xl px-4 py-3 text-sm focus:ring-1 focus:ring-turquoise outline-none text-ink" placeholder="e.g. Топ 5 пляжей Мармариса" />
            </div>
            <div className="space-y-1.5">
              <label className="block text-xs font-mono uppercase tracking-wider text-shutter">İçerik (RU) *</label>
              <textarea name="contentRu" required rows={10} defaultValue={post?.contentRu || ''} className="w-full bg-stone border border-pine/10 rounded-xl px-4 py-3 text-sm focus:ring-1 focus:ring-turquoise outline-none text-ink" placeholder="Контент..." />
            </div>
          </div>
        )}
      </div>

      <hr className="border-dashed border-pine/8" />

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
        <div className="space-y-1.5">
          <label className="block text-xs font-mono uppercase tracking-wider text-shutter">URL Slug *</label>
          <input type="text" name="slug" required defaultValue={post?.slug || ''} className="w-full bg-stone border border-pine/10 rounded-xl px-4 py-3 text-sm focus:ring-1 focus:ring-turquoise outline-none text-ink font-mono" placeholder="en-iyi-5-plaj" />
        </div>
        <div className="space-y-1.5">
          <label className="block text-xs font-mono uppercase tracking-wider text-shutter">Kapak Görseli URL</label>
          <input type="url" name="coverImageUrl" defaultValue={post?.coverImage || ''} className="w-full bg-stone border border-pine/10 rounded-xl px-4 py-3 text-sm focus:ring-1 focus:ring-turquoise outline-none text-ink" placeholder="https://..." />
        </div>
        <div className="space-y-1.5">
          <label className="block text-xs font-mono uppercase tracking-wider text-shutter">Yazar</label>
          <input type="text" name="author" defaultValue={post?.author || ''} className="w-full bg-stone border border-pine/10 rounded-xl px-4 py-3 text-sm focus:ring-1 focus:ring-turquoise outline-none text-ink" placeholder="Örn: Ayris Dev" />
        </div>
        <div className="space-y-1.5">
          <label className="block text-xs font-mono uppercase tracking-wider text-shutter">Etiketler (Virgülle ayırın)</label>
          <input type="text" name="tags" defaultValue={post?.tags?.join(', ') || ''} className="w-full bg-stone border border-pine/10 rounded-xl px-4 py-3 text-sm focus:ring-1 focus:ring-turquoise outline-none text-ink font-mono" placeholder="plaj, yaz, tatil" />
        </div>
      </div>
      
      <div className="space-y-4 pt-4 border-t border-pine/8">
        <label className="flex items-center gap-2 cursor-pointer">
          <input 
            type="checkbox" 
            name="isPublished" 
            value="true"
            defaultChecked={!!post?.publishedAt}
            className="rounded border-pine/20 text-turquoise focus:ring-turquoise" 
          />
          <span className="text-sm font-medium text-ink">Yazıyı Yayınla (Görünür Yap)</span>
        </label>
      </div>

      <div className="flex items-center justify-between pt-4">
        <Link href="/admin/blog" className="text-xs font-bold text-shutter hover:text-pine transition inline-flex items-center gap-1">
          <ArrowLeft className="w-3.5 h-3.5" />
          İptal ve Geri Dön
        </Link>
        <button disabled={loading} type="submit" className="bg-turquoise hover:bg-turquoise/90 text-paper px-6 py-3 rounded-xl font-bold text-sm transition-colors shadow-sm inline-flex items-center gap-2 disabled:opacity-50">
          <Save className="w-4 h-4" />
          {loading ? 'Kaydediliyor...' : 'Kaydet'}
        </button>
      </div>
    </form>
  )
}
