"use client";

import { useState } from "react";
import toast from "react-hot-toast";
import { useRouter } from "next/navigation";

import SelectionCo from "@/app/Components/Selection/SelectionCo";
import axios from "axios";
import { envConfig } from "@/app/lib/config";
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().toISOString().split("T")[0];
  const [date, setDate] = useState(todayISO);

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

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

  const handleSaveReceipt = async () => {
    if (!numAcount) {
      toast.error("Busca de nuevo al estudiante");
      return;
    }

    if (!plataformaSeleccionada) {
      toast.error("Selecciona una plataforma");
      return;
    }

    if (!folio) {
      toast.error("Ingresa el folio del ticket");
      return;
    }

    if (!amount) {
      toast.error("Coloca el monto a depositar");
      return;
    }

    if (!date) {
      toast.error("Coloca la fecha");
      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 },
      );

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

      setFolio("");
      setAmount("");
      setDate(todayISO);
      router.refresh();
    } catch (err: any) {
      toast.error(err.message || "Error al guardar");
    }
  };

  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) {
                    toast.error("El monto no puede superar $1000.00");
                    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