'use client'

import { useActionState, useState, useRef } from 'react'
import { createProduct, updateProduct } from './actions'
import Link from 'next/link'
import Image from 'next/image'
import { Upload, X, Loader2 } from 'lucide-react'

const DEFAULT_IMAGE = '/default-product.png'

type Category = {
  id: number
  name_tr: string
}

type Product = {
  id: number
  name_tr: string
  price: number | string
  category_id: number | null
  description_tr: string | null
  image_url: string | null
  status: number | null
}

export default function ProductForm({ categories, product }: { categories: Category[], product?: Product }) {
  const isEditing = !!product
  const actionToUse = isEditing 
    ? updateProduct.bind(null, product.id)
    : createProduct

  const [state, formAction, isPending] = useActionState(actionToUse, undefined)
  const [imageUrl, setImageUrl] = useState<string>(product?.image_url || '')
  const [uploading, setUploading] = useState(false)
  const [uploadError, setUploadError] = useState('')
  const fileInputRef = useRef<HTMLInputElement>(null)

  const previewSrc = imageUrl || DEFAULT_IMAGE

  async function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0]
    if (!file) return

    if (file.size > 5 * 1024 * 1024) {
      setUploadError("Dosya boyutu 5MB'ı geçemez.")
      return
    }

    setUploadError('')
    setUploading(true)

    try {
      const fd = new FormData()
      fd.append('file', file)
      const res = await fetch('/api/upload', { method: 'POST', body: fd })
      const data = await res.json()
      if (!res.ok) throw new Error(data.error || 'Yükleme başarısız')
      setImageUrl(data.url)
    } catch (err: any) {
      setUploadError(err.message || 'Resim yüklenirken hata oluştu.')
    } finally {
      setUploading(false)
    }
  }

  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>
      )}

      {/* Image Upload */}
      <div>
        <label className="block text-sm font-medium text-gray-700 mb-2">Ürün Resmi</label>
        <div className="flex items-start gap-4">
          {/* Preview */}
          <div className="relative w-28 h-28 rounded-xl overflow-hidden border-2 border-gray-200 bg-gray-50 flex-shrink-0">
            <Image
              src={previewSrc}
              alt="Ürün resmi önizleme"
              fill
              className="object-cover"
            />
            {imageUrl && (
              <button
                type="button"
                onClick={() => {
                  setImageUrl('')
                  if (fileInputRef.current) fileInputRef.current.value = ''
                }}
                className="absolute top-1 right-1 bg-red-500 text-white rounded-full p-0.5 hover:bg-red-600 transition-colors"
              >
                <X size={12} />
              </button>
            )}
          </div>

          {/* Upload button */}
          <div className="flex flex-col gap-2 justify-center h-28">
            <button
              type="button"
              onClick={() => fileInputRef.current?.click()}
              disabled={uploading}
              className="flex items-center gap-2 px-4 py-2 border-2 border-dashed border-gray-300 rounded-lg text-sm text-gray-600 hover:border-blue-400 hover:text-blue-600 transition-colors disabled:opacity-50"
            >
              {uploading
                ? <><Loader2 size={16} className="animate-spin" /> Yükleniyor...</>
                : <><Upload size={16} /> Resim Yükle</>
              }
            </button>
            <p className="text-xs text-gray-500">PNG, JPG, WEBP — Maks. 5MB</p>
            {uploadError && <p className="text-xs text-red-600">{uploadError}</p>}
            {!imageUrl && (
              <p className="text-xs text-gray-400 italic">Resim yüklenmezse varsayılan görsel kullanılır.</p>
            )}
          </div>
        </div>

        <input
          ref={fileInputRef}
          type="file"
          accept="image/*"
          className="hidden"
          onChange={handleFileChange}
        />
        {/* URL'yi form verisiyle gönder */}
        <input type="hidden" name="image_url" value={imageUrl} />
      </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">Ürün Adı (TR) *</label>
          <input
            type="text"
            name="name_tr"
            defaultValue={product?.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">Kategori *</label>
          <select
            name="category_id"
            defaultValue={product?.category_id?.toString() || ''}
            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"
          >
            <option value="" disabled>Seçiniz</option>
            {categories.map(c => (
              <option key={c.id} value={c.id}>{c.name_tr}</option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-gray-700 mb-1">Fiyat (₺) *</label>
          <input
            type="number"
            step="0.01"
            name="price"
            defaultValue={product ? product.price.toString() : ''}
            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>

      <div>
        <label className="block text-sm font-medium text-gray-700 mb-1">Açıklama (TR)</label>
        <textarea
          name="description_tr"
          defaultValue={product?.description_tr || ''}
          rows={3}
          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 className="flex items-center gap-2">
        <input
          type="checkbox"
          name="status"
          id="status"
          defaultChecked={product ? product.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/products"
          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 || uploading}
          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>
  )
}
