import FormBox from "../components/FormBox";
import { useState } from "react";
import FormField from "../components/FormField";
import FormInput from "../components/FormInput";
import { Search } from "lucide-react";
import Button from "../components/Button";
import { AnimatePresence } from "motion/react";
import Notification from "../components/Notification";
import { useToast } from "../hooks/useToast";
import { lockerService } from "../services/locker.service";
import { useLoading } from "../hooks/useLoading";
import { useNavigate } from "react-router-dom";
import FieldsWrapper from "../components/FieldsWrapper";

function CheckInOutManagement() {
  const [accountNumber, setAccountNumber] = useState("");
  const [notification, setNotification] = useState({
    visible: false,
    message: "",
    type: "",
  });

  const showToast = useToast();
  const { setIsLoading } = useLoading();
  const navigate = useNavigate();

  const handleNext = async (e) => {
    e.preventDefault();
    if (accountNumber === "") {
      showToast("Account Number is required", "error");
      return;
    }
    try {
      setIsLoading(true);
      const response = await lockerService.preCheckIn(accountNumber);
      console.log(response.data);
      if (response.status === 200) {
        const data = response.data;
        if (data.code === 1) {
          navigate("log", { state: { accountNumber } });
        } else if (data.code === 2) {
          setNotification({
            visible: true,
            message:
              "Monthly access limit exceeded. A fine will be charged for each additional access.",
            type: "warning",
          });
        } else if (data.code === 3) {
          setNotification({
            visible: true,
            message:
              "Rent for this account is due. Please pay the rent amount in full to access the locker.",
            type: "error",
          });
        }
      }
    } catch (error) {
      console.log(error);
      setNotification(error.message, "error");
    } finally {
      setIsLoading(false);
    }
  };
  return (
    <div>
      <AnimatePresence>
        {notification.visible && <Notification notification={notification} />}
      </AnimatePresence>
      <FormBox title="Check In/Out">
        <FieldsWrapper>
          <FormField
            label="Account Number"
            icon={{ icon: <Search size={17} />, onClick: () => {} }}
          >
            <FormInput
              props={{
                type: "text",
                value: accountNumber,
                onChange: (e) => setAccountNumber(e.target.value),
              }}
            />
          </FormField>
          </FieldsWrapper>
        <Button text="Next" onClick={handleNext} />
      </FormBox>
    </div>
  );
}

export default CheckInOutManagement;
