"use client";

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

import Selection from "../Selection/Selection";
import Cookies from "js-cookie";
import axios from "axios";

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

interface ReceiptsProps {
  numAcount: number | null;
  plataformasInscritas: string[];
}

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

export default function Inscripcion({
  numAcount,
  plataformasInscritas,
}: ReceiptsProps) {
  const [conPago, setConPago] = useState<"con" | "sin">("con");
  const [plataformaSeleccionada, setPlataformaSeleccionada] = useState<
    string | null
  >(null);

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

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

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

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

    if (!plataformaSeleccionada) {

      Swal.fire({
        title: "Selecciona una plataforma!",
        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/registration`,
        {
          monto: Number(amount),
          id_cuenta: numAcount,
          id_plataforma,
          folio_recibo: folio,
          fecha_recibo: date,
          realizo_pago: true,
        },
        { headers },
      );

      Swal.fire({
        title: "Alumno inscrito con pago",
        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
      });
    }
  };

  const handleInscripcionSinPago = async () => {
    if (!numAcount) {

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

    const id_plataforma = PLATAFORMA_MAP[plataformaSeleccionada];

    try {
      const res = await fetch(`${envConfig.apiUrl}/alumno-inscrito`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          id_cuenta: numAcount,
          id_plataforma,
          realizo_pago: false,
        }),
      });

      const data = await res.json();

      if (!res.ok) {
        Swal.fire("Error");
        throw new Error(data.message || "Error al inscribir");
      }


      Swal.fire({
        title: "Alumno inscrito sin pago!",
        icon: "success",
        draggable: true,
      });
      router.refresh();
    } catch (err: any) {
      Swal.fire({
        title: err.message,
        icon: "error",
        draggable: true,
      });
    }
  };

  return (
    <section>
      <Selection
        plataformasInscritas={plataformasInscritas}
        onSelect={setPlataformaSeleccionada}
      />

      <select
        value={conPago}
        onChange={(e) => setConPago(e.target.value as "con" | "sin")}
        style={{
          maxWidth: "120px",
          minWidth: "120px",
        }}
      >
        <option value="con">con pago</option>
        <option value="sin">sin pago</option>
      </select>

      {conPago === "con" && (
        <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" disabled={!plataformaSeleccionada}
              >Inscribir</button>
              <button
                type="button"
                className={`button buttonCancel ${lock ? "buttonLock" : "buttonOpenLock"
                  }`}
                onClick={() => {
                  setLock((prev) => !prev);
                  setAmount("");
                }}
              />
            </div>
          </div>
        </form>
      )}
      {conPago === "sin" && (
        <div className="containerButton">
          <button
            className="button buttonSearch"
            disabled={!plataformaSeleccionada}
            onClick={handleInscripcionSinPago}
          >
            Inscribir
          </button>
        </div>
      )}
    </section>
  );
}
//IO
