import { useEffect, useState } from "react";

type Props = {
  updateIdList: (cids: string[]) => void;
};

export default function IdComponent({ updateIdList }: Props) {
  let [idSet, setIdSet] = useState<Set<string>>(new Set());
  let onValidId = (id: string) => {
    setIdSet((prev) => new Set(prev.add(id)));
  };
  let removeCid = (id: string) => {
    setIdSet((prev) => new Set([...prev].filter((x) => x !== id)));
  };
  useEffect(() => {
    updateIdList([...idSet]);
  }, [idSet]);
  return (
    <div className="flex justify-center">
      <div className="flex flex-col gap-2">
        {Array.from(idSet).map((v) => (
          <FixedId cid={v} removeCid={removeCid} key={v} />
        ))}
        <SingleIdComponent onValidId={onValidId} />
      </div>
    </div>
  );
}

type FixedIdProps = {
  cid: string;
  removeCid: (cid: string) => void;
};

function FixedId({ cid, removeCid }: FixedIdProps) {
  return (
    <div className="flex gap-2">
      <input type="text" className="border-2" disabled value={cid} />
      <button
        className="bg-red-300 p-2 rounded-md"
        onClick={() => removeCid(cid)}
      >
        ลบ
      </button>
    </div>
  );
}

type SingleIdProps = {
  onValidId: (cid: string) => void;
};

function SingleIdComponent({ onValidId }: SingleIdProps) {
  let [isValid, setIsValid] = useState(false);
  let [cid, setCid] = useState("");
  useEffect(() => {
    let isValidId = isValidThaiID(cid);
    setIsValid(isValidId);
    if (isValidId) {
      onValidId(cid);

      setCid("");
    }
  }, [cid]);
  return (
    <div className="flex gap-2">
      <input
        type="text"
        className="border-2"
        onChange={(v) => setCid(v.target.value)}
        value={cid}
      />
      {isValid ? <p>OK</p> : null}
    </div>
  );
}

function isValidThaiID(id: string) {
  if (!/^\d{13}$/.test(id)) {
    return false;
  }
  let sum = 0;
  for (let i = 0; i < 12; i++) {
    sum += Number(id[i]) * (13 - i);
  }
  const checkSum = (11 - (sum % 11)) % 10;
  return checkSum === Number(id[12]);
}
