"use client";

import Cookies from "js-cookie";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { PostImpressions } from "@/app/lib/postImpressions";
import Swal from "sweetalert2";

interface CostOption {
  value: number;
}

interface ImpressionsProps {
  costs: CostOption[];
  numAcount: number | null;
  id_servicio: number;
}

function Impressions({ costs, numAcount, id_servicio }: ImpressionsProps) {
  const [pages, setPages] = useState("");
  const [cost, setCost] = useState(String(costs[0].value));

  const total = Number(cost) * Number(pages);

  const router = useRouter();
  const handleLogout = () => {
    Cookies.remove("token");
    Cookies.remove("session");
    router.push("/Login");
  };

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

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

    if (!pages) {

      Swal.fire({
        title: "Ingresa el numero de hojas a imprimir!",
        icon: "error",
        draggable: true
      });
      return;
    }

    if (!cost) {

      Swal.fire({
        title: "Selecciona un costo!",
        icon: "error",
        draggable: true
      });
      return;
    }

    const result = await PostImpressions({
      id_cuenta: numAcount,
      numero_hojas: parseInt(pages),
      monto: total,
      id_servicio,
    });

    if (result?.error) {
      if (result.message === "Token inválido") {
        handleLogout();
      } else {
        Swal.fire({
          title: result.message,
          icon: "error",
          draggable: true
        });
      }
      return;
    }

    setPages("");
    setCost(String(costs[0].value));

    Swal.fire({
      title: "Impresion cobrada correctamente!",
      icon: "success",
      draggable: true
    });
    router.refresh();
  };

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault();
        handlePayment();
      }}
    >
      <div className="gap">
        <div className="groupInput">
          <label className="label">Costo:</label>
          <select value={cost} onChange={(e) => setCost(e.target.value)}>
            <option value="">Selecciona el costo</option>
            {costs.map((c) => (
              <option key={c.value} value={c.value}>
                ${c.value}
              </option>
            ))}
          </select>
        </div>

        <div className="groupInput">
          <label className="label">Hojas:</label>
          <input
            type="text"
            value={pages}
            onChange={(e) => {
              const value = e.target.value;
              if (/^\d*$/.test(value)) {
                setPages(value);
              }
            }}
            placeholder="Numero de hojas a imprimir..."
            inputMode="numeric"
            pattern="[0-9]*"
          />
        </div>

        <div
          className="groupInput total"
        >
          <label className="label">Total:</label>
          <label
            style={{ width: "100%", minWidth: "200px", maxWidth: "500px" }}
          >
            {pages && cost && `$${total}.00`}
          </label>
        </div>

        <div className="containerButton">
          <button className="button buttonCharge" type="submit">
            Cobrar
          </button>
        </div>
      </div>
    </form>
  );
}

export default Impressions;
//IO
