"use client";

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

import "./Receipt.css";
import Selection from "../Selection/Selection";
import { envConfig } from "@/app/lib/config";

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 [date, setDate] = useState("");

  //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) {
      toast.error("busca de nuevo al estudiante");
      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;
    }

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

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

      toast.success("Recibo guardado");
      router.refresh();
    } catch (err: any) {
      toast.error(String(err));
    }
  };

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

    if (!plataformaSeleccionada) {
      toast.error("Selecciona una plataforma");
      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) {
        throw new Error(data.message || "Error al inscribir");
      }

      toast.success("Alumno inscrito sin pago");
      router.refresh();
    } catch (err: any) {
      toast.error(err.message);
    }
  };

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

      <select
        value={conPago}
        onChange={(e) => setConPago(e.target.value as "con" | "sin")}
        style={{
          marginBottom: "1rem",
          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);
                  }
                }}
              />
            </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 (value === "" || numericValue <= 1000) {
                      setAmount(value);
                    }
                  }
                }}
              />
            </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">
              <button className="button buttonSearch">Inscribir</button>
            </div>
          </div>
        </form>
      )}
      {conPago === "sin" && (
        <div className="containerButton">
          <button
            className="button buttonSearch"
            disabled={!plataformaSeleccionada}
            onClick={handleInscripcionSinPago}
          >
            Inscribir
          </button>
        </div>
      )}
    </section>
  );
}
//IO
