"use client";

import { LocationContext } from "@/components/locationContext";
import { useContext, useState } from "react";
import { updateZone } from "./action";

export default function TotalSetter() {
  const locationContext = useContext(LocationContext);
  const [total, setTotal] = useState<number>(0);
  async function submit() {
    if (
      locationContext?.zone[0] == undefined ||
      locationContext?.province[0] == undefined
    ) {
      alert("ยังไม่ได้เลือกพื้นที่");
      return;
    }
    await updateZone(
      locationContext.province[0],
      locationContext.zone[0],
      total,
    );
    alert(`อัพเดทสำเร็จ`);
  }
  return (
    <div>
      <div className="flex">
        จำนวนทั้งหมด:{" "}
        <input
          value={total}
          className="rounded-md border-2"
          type="number"
          onChange={(e) =>
            setTotal(
              e.currentTarget.value !== ""
                ? parseInt(e.currentTarget.value)
                : 0,
            )
          }
        />
      </div>
      <button className="rounded-md bg-green-300 p-2" onClick={submit}>
        ยืนยัน
      </button>
    </div>
  );
}
