'use client';

import React, { useState } from 'react';
import dynamic from 'next/dynamic';
import { Scanner } from '@yudiel/react-qr-scanner';
import Button from '@/components/button';
import axiosInstance from '@/utils/api-config';
import toast from 'react-hot-toast';

const Modal = dynamic(() => import('@/components/modal'), { ssr: false });

export default function Page() {
  const [showModal, setShowModal] = useState(false);
  const [enableScan, setEnableScan] = useState(true);
  const [statusMessage, setStatusMessage] = useState('');

  const [participante, setParticipante] = useState('');
  const [contador, setContador] = useState(0);
  const [message, setMessage] = useState('');
  const [token, setToken] = useState('');
  const [tokenValid, setTokenValid] = useState(false);

  const handleScan = async (rawValue: string) => {
    console.log('QR Escaneado:', rawValue);
    if (!enableScan) return;

    if (!rawValue) {
      setStatusMessage('⚠️ El QR no contiene los campos requeridos');
      return;
    }

    try {
      const response = await axiosInstance.post(
        '/participante-evento/decode-token',
        { token: rawValue }
      );

      if (response.data) {
        // Token válido
        setToken(rawValue);
        setTokenValid(true);
        setShowModal(true);
        setEnableScan(false);
        setContador(response.data.contador);
      } else {
        // Token caducado o cualquier otro error
        setStatusMessage(`❌ Error el código qr ya caduco`);
        setTokenValid(false);
        setShowModal(true); // mostramos modal con el mensaje de error
        setEnableScan(false);
      }
    } catch (err) {
      console.error('Error al decodificar el QR:', err);
      setStatusMessage('❌ Error al leer el QR');
      setTokenValid(false);
      setShowModal(true);
      setEnableScan(false);
    }
  };

  const handleConfirm = async () => {
    if (!tokenValid) return;

    try {
      const response = await axiosInstance.post(
        `/participante-evento/asistencia`,
        {
          token: token,
        }
      );

      //Validacion
      if (response.data.success === false) {
        console.error('El usuario ya se registro');
        setMessage(response.data.message);
        toast.error('❌ Error el usaurio ya se registro previamente.');
      } else {
        setParticipante(response.data.data.participante);
        setMessage(response.data.message);
        console.log('Asistencia registrada:', response.data);
        toast.success('✅ Asistencia registrada correctamente');
      }
    } catch (err) {
      console.error('Error en la petición:', err);
      setStatusMessage('❌ Error de red al registrar asistencia');
    }

    setShowModal(false);
    setEnableScan(true);
  };

  return (
    <main className="container-fluid flex-grow-1 d-flex flex-column justify-content-center py-4">
      <div className="row justify-content-center">
        <div className="col-12 col-md-8 col-lg-6 col-xl-5">
          <div className="card shadow border-0 rounded-3">
            <div className="card-header bg-primary text-white text-center py-4 border-0">
              <div className="mb-3">
                <i className="bi bi-qr-code-scan display-4"></i>
              </div>
              <h2 className="mb-2 fw-bold">Registro de Asistencia</h2>
              <p className="mb-0 opacity-75">
                Escanea el código QR para registrar la asistencia
              </p>
            </div>

            <div className="card-body p-4">
              {enableScan ? (
                <div className="text-center">
                  <div className="mb-4 mx-auto position-relative d-inline-block">
                    <div className="border border-3 border-primary rounded-3 p-3 bg-light">
                      <Scanner
                        onScan={(codes) => {
                          if (codes.length > 0) {
                            handleScan(codes[0].rawValue);
                          }
                        }}
                        onError={(err) => console.error('QR Error:', err)}
                        constraints={{ facingMode: 'environment' }}
                        styles={{
                          container: {
                            width: '100%',
                            maxWidth: '300px',
                            borderRadius: '8px',
                            overflow: 'hidden',
                          },
                        }}
                      />
                    </div>
                  </div>

                  <div className="mb-4">
                    <div className="alert alert-info border-0 rounded-3 d-flex align-items-center">
                      <i className="bi bi-info-circle-fill me-2"></i>
                      <small>
                        Mantén el código QR centrado en el marco de la cámara
                      </small>
                    </div>
                  </div>

                  {participante && (
                    <div className="mb-4">
                      <div className="alert alert-success border-0 rounded-3 d-flex align-items-center">
                        <i className="bi bi-person-check-fill me-2"></i>
                        <span>
                          Ultimo participante registrado: {participante}
                        </span>
                      </div>
                    </div>
                  )}

                  {message && (
                    <div className="mb-4">
                      <div className="alert alert-info border-0 rounded-3 d-flex align-items-center">
                        <i className="bi bi-info-circle-fill me-2"></i>
                        <span>{message}</span>
                      </div>
                    </div>
                  )}

                  <Button
                    onClick={() => setEnableScan(false)}
                    variant="outline-danger"
                    className="px-4 py-2 rounded-pill"
                  >
                    <i className="bi bi-camera-video-off me-2"></i>
                    Detener cámara
                  </Button>
                </div>
              ) : (
                <div className="text-center py-5">
                  <div className="mb-4">
                    <i
                      className="bi bi-camera-video-off-fill text-muted"
                      style={{ fontSize: '4rem' }}
                    ></i>
                  </div>
                  <h4 className="text-muted mb-3">Cámara desactivada</h4>
                  <p className="text-muted mb-4 lead">
                    La cámara está detenida. Actívala para continuar escaneando
                    códigos QR.
                  </p>
                  <Button
                    onClick={() => setEnableScan(true)}
                    variant="primary"
                    className="px-4 py-2 rounded-pill"
                  >
                    <i className="bi bi-camera-video me-2"></i>
                    Activar cámara
                  </Button>
                </div>
              )}

              {statusMessage && (
                <div className="mt-4">
                  <div
                    className={`alert border-0 rounded-3 d-flex align-items-center ${
                      statusMessage.includes('❌')
                        ? 'alert-danger'
                        : statusMessage.includes('⚠️')
                          ? 'alert-warning'
                          : 'alert-success'
                    }`}
                  >
                    <div className="me-2">
                      {statusMessage.includes('❌') && (
                        <i className="bi bi-exclamation-triangle-fill"></i>
                      )}
                      {statusMessage.includes('⚠️') && (
                        <i className="bi bi-exclamation-circle-fill"></i>
                      )}
                      {!statusMessage.includes('❌') &&
                        !statusMessage.includes('⚠️') && (
                          <i className="bi bi-check-circle-fill"></i>
                        )}
                    </div>
                    <span>{statusMessage}</span>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      <Modal
        isVisible={showModal}
        size="md"
        onClose={() => {
          setShowModal(false);
          setEnableScan(true);
          setTokenValid(false);
        }}
        closeButton
        className={{
          content: 'border-0 rounded-3',
          body: 'text-center',
        }}
      >
        <div className="modal-header bg-success text-white border-0 rounded-top-3">
          <h5 className="modal-title mb-0 fw-bold">
            <i className="bi bi-check-circle-fill me-2"></i>
            QR Escaneado Correctamente
          </h5>
        </div>

        <div className="modal-body p-4">
          {tokenValid ? (
            // Modal de confirmación de asistencia
            <>
              <p className="text-muted mb-3">
                Contador del usuario: <strong>{contador}</strong>
              </p>
              <div className="d-grid gap-2 d-md-flex justify-content-center">
                <Button
                  variant="success"
                  onClick={handleConfirm}
                  className="px-4 py-2 rounded-pill fw-semibold"
                >
                  <i className="bi bi-check2 me-2"></i>
                  Confirmar Asistencia
                </Button>
                <Button
                  variant="outline-secondary"
                  onClick={() => {
                    setShowModal(false);
                    setEnableScan(true);
                    setTokenValid(false);
                    setToken('');
                  }}
                  className="px-4 py-2 rounded-pill"
                >
                  <i className="bi bi-x-lg me-2"></i>
                  Cancelar
                </Button>
              </div>
            </>
          ) : (
            // Modal de error
            <div className="py-4">
              <div className="mb-3">
                <i
                  className="bi bi-exclamation-triangle-fill text-warning"
                  style={{ fontSize: '2.5rem' }}
                ></i>
              </div>
              <h6 className="text-danger mb-0">{statusMessage}</h6>
              <div className="mt-3">
                <Button
                  variant="secondary"
                  onClick={() => {
                    setShowModal(false);
                    setEnableScan(true);
                    setStatusMessage('');
                  }}
                  className="px-4 py-2 rounded-pill"
                >
                  Cerrar
                </Button>
              </div>
            </div>
          )}
        </div>
      </Modal>
    </main>
  );
}
