'use client'

import { useActionState } from 'react'
import { createCategory, updateCategory } from './actions'
import Link from 'next/link'

type Category = {
  id: number
  name_tr: string
  order_num: number | null
  status: number | null
}

export default function CategoryForm({ category }: { category?: Category }) {
  const isEditing = !!category
  
  // Use appropriate action based on editing state
  const actionToUse = isEditing 
    ? updateCategory.bind(null, category.id)
    : createCategory

  const [state, formAction, isPending] = useActionState(actionToUse, undefined)

  return (
    <form action={formAction} className="space-y-6">
      {state?.error && (
        <div className="bg-red-50 text-red-700 p-3 rounded-lg text-sm">
          {state.error}
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Kategori Adı (TR) *
          </label>
          <input
            type="text"
            name="name_tr"
            defaultValue={category?.name_tr || ''}
            required
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-colors"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">
            Sıra Numarası
          </label>
          <input
            type="number"
            name="order_num"
            defaultValue={category?.order_num || 0}
            className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 outline-none transition-colors"
          />
        </div>
      </div>

      <div className="flex items-center gap-2">
        <input
          type="checkbox"
          name="status"
          id="status"
          defaultChecked={category ? category.status === 1 : true}
          className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
        />
        <label htmlFor="status" className="text-sm font-medium text-gray-700">
          Aktif
        </label>
      </div>

      <div className="flex justify-end gap-3 pt-4 border-t">
        <Link href="/admin/categories" className="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg font-medium hover:bg-gray-50 transition-colors">
          İptal
        </Link>
        <button
          type="submit"
          disabled={isPending}
          className="bg-blue-600 hover:bg-blue-700 text-white font-medium py-2 px-6 rounded-lg transition-colors disabled:opacity-70"
        >
          {isPending ? 'Kaydediliyor...' : 'Kaydet'}
        </button>
      </div>
    </form>
  )
}
