"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { AdminDialog } from "@/components/ui/admin-dialog";
import { createProduct, toggleProductActive } from "./actions";

type ProductRow = {
  id: string;
  code: string;
  name: string;
  description: string | null;
  isActive: boolean;
};

function ProductFormFields({ product }: { product?: ProductRow }) {
  return (
    <div className="space-y-3">
      <div>
        <label className="block text-xs font-medium text-neutral-700 mb-1">Product Code *</label>
        <input name="code" defaultValue={product?.code} required disabled={!!product}
          className="w-full rounded-lg border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 disabled:bg-neutral-50 disabled:text-neutral-400"
          placeholder="e.g. FUEL-OIL-001" />
        {product && <p className="mt-1 text-xs text-neutral-400">Product code cannot be changed after creation.</p>}
      </div>
      <div>
        <label className="block text-xs font-medium text-neutral-700 mb-1">Name *</label>
        <input name="name" defaultValue={product?.name} required
          className="w-full rounded-lg border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20" />
      </div>
      <div>
        <label className="block text-xs font-medium text-neutral-700 mb-1">Description</label>
        <textarea name="description" defaultValue={product?.description ?? ""} rows={2}
          className="w-full rounded-lg border border-neutral-300 px-3 py-2 text-sm focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 resize-none" />
      </div>
    </div>
  );
}

export function AddProductButton() {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [pending, setPending] = useState(false);
  const [error, setError] = useState("");

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setPending(true);
    setError("");
    const result = await createProduct(new FormData(e.currentTarget));
    if ("error" in result) { setError(result.error); setPending(false); }
    else { setOpen(false); router.refresh(); }
  }

  return (
    <>
      <button onClick={() => setOpen(true)}
        className="rounded-lg bg-primary-600 px-4 py-2.5 text-sm font-semibold text-white hover:bg-primary-700 transition-colors">
        + Add Product
      </button>
      <AdminDialog title="Add Product" open={open} onClose={() => setOpen(false)}>
        <form onSubmit={handleSubmit} className="space-y-4">
          <ProductFormFields />
          {error && <p className="text-sm text-danger-700 bg-danger-50 rounded-lg px-3 py-2">{error}</p>}
          <div className="flex justify-end gap-3 pt-1">
            <button type="button" onClick={() => setOpen(false)}
              className="rounded-lg border border-neutral-300 px-4 py-2 text-sm font-medium text-neutral-700 hover:bg-neutral-50">
              Cancel
            </button>
            <button type="submit" disabled={pending}
              className="rounded-lg bg-primary-600 px-4 py-2 text-sm font-semibold text-white hover:bg-primary-700 disabled:opacity-60">
              {pending ? "Creating…" : "Create Product"}
            </button>
          </div>
        </form>
      </AdminDialog>
    </>
  );
}

export function ToggleProductButton({ product }: { product: ProductRow }) {
  const router = useRouter();
  const [toggling, setToggling] = useState(false);

  async function handleToggle() {
    setToggling(true);
    await toggleProductActive(product.id);
    router.refresh();
    setToggling(false);
  }

  return (
    <button onClick={handleToggle} disabled={toggling}
      className={`text-sm font-medium ${product.isActive ? "text-danger-600 hover:text-danger-700" : "text-success-600 hover:text-success-700"}`}>
      {toggling ? "…" : product.isActive ? "Deactivate" : "Activate"}
    </button>
  );
}
