"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { envConfig } from "@/app/lib/config";

import SelectionCo from "@/app/Components/Selection/SelectionCo";
import axios from "axios";
import Cookies from "js-cookie";
import Swal from "sweetalert2";

import "./addTime.css";

const PLATAFORMA_MAP: Record<string, number> = {
  WINDOWS: 1,
  MACINTOSH: 2,
  PROFESORES: 5,
};

interface AddTimeProps {
  numAcount: number;
  plataformasInscritas: string[];
}

export default function AddTime({
  numAcount,
  plataformasInscritas,
}: AddTimeProps) {
  const router = useRouter();

  const [plataformaSeleccionada, setPlataformaSeleccionada] = useState<
    string | null
  >(null);

  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);

  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];

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

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

    if (!plataformaSeleccionada) {

      Swal.fire({
        title: "Selecciona una plataforma!",
        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;
    }

    const id_plataforma = PLATAFORMA_MAP[plataformaSeleccionada];

    try {
      const token = Cookies.get("token");
      const headers = { Authorization: `Bearer ${token}` };

      await axios.post(
        `${envConfig.apiUrl}/operations/time`,
        {
          monto: Number(amount),
          id_cuenta: numAcount,
          idPlataforma: id_plataforma,
          folio_recibo: folio,
          fecha_recibo: date,
        },
        { headers },
      );


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

      setFolio("");
      setAmount("");
      setDate(todayISO);
      router.refresh();
    } catch (error: any) {
      const msg =
        error.response?.data?.message ||
        error.message ||
        "Error desconocido al crear recibo";
      Swal.fire({
        title: msg,
        icon: "error",
        draggable: true,
      });
    }
  };

  return (
    <div className="addTime">
      <SelectionCo
        plataformasInscritas={plataformasInscritas}
        onSelect={setPlataformaSeleccionada}
      />

      <form
        onSubmit={(e) => {
          e.preventDefault();
          handleSaveReceipt();
        }}
      >
        <div className="gap">
          <div className="groupInput">
            <label className="label">Ticket:</label>
            <input
              type="text"
              value={folio}
              onChange={(e) => {
                const value = e.target.value;
                if (/^\d*$/.test(value) && value.length <= 7) {
                  setFolio(value);
                }
              }}
              placeholder="Numero de ticket..."
              inputMode="numeric"
            />
          </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"
            />
          </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>
    </div>
  );
}
//IO
