"use client";

import { useContext, useEffect, useState } from "react";
import { LocationContext } from "../locationContenxt";

type Props = {
  provinces: Province[];
};
type Province = {
  id: number;
  name: string;
  zones: Zone[];
};
type Zone = {
  id: number;
  name: string;
  province: number;
};
export default function LocationSelector({ provinces }: Props) {
  let [provinceId, setProvinceId] = useState<number | undefined>(undefined);
  let [amphurList, setAmphurList] = useState<Zone[] | undefined>(undefined);
  let [amphurId, setAmphurId] = useState<number | undefined>(undefined);
  const locationContext = useContext(LocationContext);
  function setProvince(_id: string) {
    let id = parseInt(_id);
    setProvinceId(id);
    let province = provinces.find((p) => p.id == id);
    if (province == undefined) return;
    setAmphurList(province.zones);
    setAmphurId(undefined);
  }
  function setAmphur(_id: string) {
    let id = parseInt(_id);
    setAmphurId(id);
  }
  useEffect(() => {
    if (locationContext == undefined) return;
    if (amphurId == undefined || provinceId == undefined) {
      locationContext.zone[1](undefined);
      locationContext.province[1](undefined);
      return;
    }

    locationContext.zone[1](amphurId);
    locationContext.province[1](provinceId);
  }, [amphurId]);
  return (
    <div className="flex flex-col gap-2">
      <div className="flex gap-2">
        จังหวัด:
        <select
          value={provinceId}
          className="flex-1"
          onChange={(e) => setProvince(e.currentTarget.value)}
        >
          <option value={undefined} hidden>
            None
          </option>
          {provinces.map((p) => (
            <option key={p.id} value={p.id}>
              {p.name}
            </option>
          ))}
        </select>
      </div>

      {amphurList && (
        <div className="flex gap-2">
          อำเภอ:
          <select
            value={amphurId}
            className="flex-1"
            onChange={(e) => setAmphur(e.currentTarget.value)}
          >
            <option value={undefined} hidden>
              None
            </option>
            {amphurList.map((a) => (
              <option key={a.id} value={a.id}>
                {a.name}
              </option>
            ))}
          </select>
        </div>
      )}
    </div>
  );
}
