"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";

const statuses = ["PENDING","CONFIRMED","PROCESSING","SHIPPED","DELIVERED","CANCELLED"];

export default function AdminOrderStatus({ orderId, currentStatus }: { orderId: string; currentStatus: string }) {
  const [value, setValue] = useState(currentStatus);
  const [loading, setLoading] = useState(false);
  const router = useRouter();

  const handleChange = async (newStatus: string) => {
    setValue(newStatus);
    setLoading(true);
    const res = await fetch(`/api/admin/orders/${orderId}`, {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ status: newStatus }),
    });
    setLoading(false);
    if (res.ok) { toast.success("Order updated"); router.refresh(); }
    else { toast.error("Update failed"); setValue(currentStatus); }
  };

  return (
    <select value={value} onChange={(e) => handleChange(e.target.value)} disabled={loading}
      className="text-xs border border-slate-200 rounded-lg px-2 py-1.5 focus:border-sky-400 focus:outline-none disabled:opacity-50 bg-white">
      {statuses.map((s) => <option key={s}>{s}</option>)}
    </select>
  );
}
