"use client";

import { useState } from "react";
import { PostReceipt } from "@/app/lib/postReceipt";
import { useRouter } from "next/navigation";

import Swal from "sweetalert2";
import "./Receipt.css";

interface ReceiptsProps {
  numAcount: number | null;
}

export default function Receipt({ numAcount }: ReceiptsProps) {
  const router = useRouter();

  const [folio, setFolio] = useState("");
  const [amount, setAmount] = useState("");
  const [lock, setLock] = useState<boolean>(true);
  const todayISO = new Date().toLocaleDateString("en-CA");
  const [date, setDate] = useState(todayISO);

  //restrict this month//
  const day = new Date();
  const year = day.getFullYear();
  const month = day.getMonth();
  const today = day.getDate();

  let minMount = month
  if(!lock){
    minMount = month-1
  }

  const minFecha = new Date(year, minMount, 1).toISOString().split("T")[0];
  const maxFecha = new Date(year, month, today).toISOString().split("T")[0];
  //restrict this month//

  const handleSaveReceipt = async () => {
    if (numAcount == null) {

      Swal.fire({
        title: "busca de nuevo al estudiante!",
        icon: "error",
        draggable: true
      });
      return;
    }

    if (!folio) {

      Swal.fire({
        title: "Ingresa el folio del ticket!",
        icon: "error",
        draggable: true
      });
      return;
    }

    if (!amount) {

      Swal.fire({
        title: "Coloca el monto a depositar!",
        icon: "error",
        draggable: true
      });
      return;
    }

    if (!date) {

      Swal.fire({
        title: "Coloca la fecha!",
        icon: "error",
        draggable: true
      });
      return;
    }

    try {
      await PostReceipt({
        id_cuenta: numAcount,
        folio_recibo: folio,
        monto: Number(amount),
        fecha_recibo: date,
      });

      setFolio("");
      setAmount("");
      setDate(todayISO);


      Swal.fire({
        title: "Recibo Guardado Correctamente!",
        icon: "success",
        draggable: true
      });

      router.refresh();
    } catch (err: any) {
      Swal.fire({
        title: err,
        icon: "error",
        draggable: false
      });
    }
  };

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        handleSaveReceipt();
      }}
    >
      <div className="gap">
        <div className="groupInput">
          <label className="label">Ticket:</label>
          <input
            type="text"
            value={folio}
            onChange={(error) => {
              const value = error.target.value;
              if (/^\d*$/.test(value) && value.length <= 7) {
                setFolio(value);
              }
            }}
            placeholder="Numero de tiket..."
            inputMode="numeric"
            pattern="[0-9]*"
          />
        </div>

        <div className="groupInput">
          <label className="label">Monto:</label>
          <input
            type="text"
            value={amount}
            onChange={(e) => {
              const value = e.target.value;

              if (/^\d*\.?\d*$/.test(value)) {
                const numericValue = parseFloat(value);

                if (lock && numericValue > 1000) {

                  Swal.fire({
                    title:
                      "El monto no puede superar $1000.00 Desbloquea el candado !",
                    icon: "error",
                    draggable: true,
                  });
                  return;
                }

                if (numericValue > 10000) {

                  Swal.fire({
                    title:
                      "El monto no puede superar $10000.00 pesos",
                    icon: "error",
                    draggable: true,
                  });
                  return;
                }

                setAmount(value);
              }
            }}
            placeholder="Monto recibido..."
            inputMode="numeric"
            pattern="^\d*\.?\d+$"
          />
        </div>

        <div className="groupInput">
          <label className="label">Fecha de Pago:</label>
          <input
            type="date"
            value={date}
            onChange={(e) => setDate(e.target.value)}
            min={minFecha}
            max={maxFecha}
          />
        </div>

        <div className="containerButton" style={{ position: 'relative' }}>
          <button className="button buttonSearch" type="submit">Guardar</button>
          <button
            type="button"
            className={`button buttonCancel ${lock ? "buttonLock" : "buttonOpenLock"
              }`}
            onClick={() => {
              setLock((prev) => !prev)
              setAmount('');
            }}
          />
        </div>
      </div>
    </form>
  );
}
//IO
