'use client';

import Link from 'next/link';
import { useActionState } from 'react';
import { deleteProductAction, saveProductAction, type FormState } from '@/app/admin/actions';
import type { Category, Product } from '@/lib/types';

const initial: FormState = { status: 'idle' };

export default function ProductForm({
  product,
  categories,
}: {
  product?: Product;
  categories: Category[];
}) {
  const [state, action, pending] = useActionState(saveProductAction, initial);

  return (
    <>
      <form action={action} className="space-y-6">
        {product && <input type="hidden" name="id" value={product.id} />}

        <section className="rounded-2xl border border-cocoa-800/10 bg-white p-6">
          <h2 className="font-display text-xl">Ürün bilgileri</h2>
          <div className="mt-5 space-y-5">
            <div>
              <label htmlFor="name" className="field-label">
                Ürün adı *
              </label>
              <input
                id="name"
                name="name"
                required
                defaultValue={product?.name}
                className="field"
                placeholder="Su Böreği Lüks 2 Peynirli"
              />
            </div>

            <div>
              <label htmlFor="description" className="field-label">
                Açıklama
              </label>
              <textarea
                id="description"
                name="description"
                rows={3}
                defaultValue={product?.description ?? ''}
                className="field resize-y"
                placeholder="Beyaz peynir ve yöresel peynir harmanı"
              />
            </div>

            <div className="grid gap-5 sm:grid-cols-3">
              <div>
                <label htmlFor="category_id" className="field-label">
                  Kategori *
                </label>
                <select
                  id="category_id"
                  name="category_id"
                  required
                  defaultValue={product?.category_id ?? categories[0]?.id}
                  className="field"
                >
                  {categories.map((c) => (
                    <option key={c.id} value={c.id}>
                      {c.name}
                    </option>
                  ))}
                </select>
              </div>
              <div>
                <label htmlFor="unit" className="field-label">
                  Birim
                </label>
                <input
                  id="unit"
                  name="unit"
                  defaultValue={product?.unit ?? ''}
                  className="field"
                  placeholder="Tepsi / Kg / 100 gr"
                />
              </div>
              <div>
                <label htmlFor="price" className="field-label">
                  Fiyat (₺)
                </label>
                <input
                  id="price"
                  name="price"
                  inputMode="decimal"
                  defaultValue={product?.price ?? ''}
                  className="field"
                  placeholder="Boş bırakılabilir"
                />
              </div>
            </div>

            <div className="grid gap-5 sm:grid-cols-[1fr_140px]">
              <div>
                <label htmlFor="image_url" className="field-label">
                  Görsel bağlantısı
                </label>
                <input
                  id="image_url"
                  name="image_url"
                  defaultValue={product?.image_url ?? ''}
                  className="field"
                  placeholder="https://… (boşsa kategori ikonu gösterilir)"
                />
              </div>
              <div>
                <label htmlFor="sort_order" className="field-label">
                  Sıra
                </label>
                <input
                  id="sort_order"
                  name="sort_order"
                  type="number"
                  min={1}
                  defaultValue={product?.sort_order ?? 99}
                  className="field"
                />
              </div>
            </div>

            <div className="flex flex-wrap gap-6 border-t border-cocoa-800/8 pt-5">
              <Toggle
                name="is_active"
                label="Sitede yayında"
                defaultChecked={product?.is_active ?? true}
              />
              <Toggle
                name="is_featured"
                label="Anasayfada öne çıkar"
                defaultChecked={product?.is_featured ?? false}
              />
            </div>
          </div>
        </section>

        {state.status === 'error' && (
          <p className="rounded-xl bg-red-50 px-4 py-3 text-sm text-red-700">{state.message}</p>
        )}
        {state.status === 'ok' && (
          <p className="rounded-xl bg-green-50 px-4 py-3 text-sm text-green-800">{state.message}</p>
        )}

        <div className="flex flex-wrap items-center gap-3">
          <button type="submit" disabled={pending} className="btn-primary disabled:opacity-60">
        {pending ? 'Kaydediliyor…' : 'Kaydet'}
      </button>
          <Link href="/admin/urunler" className="btn-outline">
            Listeye dön
          </Link>
        </div>
      </form>

      {product && (
        <form action={deleteProductAction} className="mt-10 border-t border-cocoa-800/10 pt-6">
          <input type="hidden" name="id" value={product.id} />
          <p className="text-sm text-cocoa-500">
            Bu ürünü kalıcı olarak silmek istiyorsanız:
          </p>
          <button
            type="submit"
            className="btn mt-3 border border-red-300 text-red-700 hover:bg-red-50"
          >
            Ürünü sil
          </button>
        </form>
      )}
    </>
  );
}

function Toggle({
  name,
  label,
  defaultChecked,
}: {
  name: string;
  label: string;
  defaultChecked: boolean;
}) {
  return (
    <label className="flex cursor-pointer items-center gap-2.5 text-sm text-cocoa-700">
      <input
        type="checkbox"
        name={name}
        defaultChecked={defaultChecked}
        className="h-4 w-4 rounded border-cocoa-800/30 text-gold-500 focus:ring-gold-400"
      />
      {label}
    </label>
  );
}

