'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 [scannedData, setScannedData] = useState<{
    id_participante: number;
    id_cuestionario: number;
  } | null>(null);

  const [showModal, setShowModal] = useState(false);
  const [enableScan, setEnableScan] = useState(true);
  const [statusMessage, setStatusMessage] = useState('');

  const [participante, setParticipante] = useState('');

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

    try {
      const data = JSON.parse(rawValue);
      if (data.id_participante && data.id_cuestionario) {
        try {
          const response = await axiosInstance.get(
            `/participante-evento/${data.id_participante}/${data.id_cuestionario}`
          );

          setParticipante(response.data.participante.correo);
          setScannedData({
            id_participante: data.id_participante,
            id_cuestionario: data.id_cuestionario,
          });
          setShowModal(true);
          setEnableScan(false);
        } catch (err) {
          console.warn('Participante no registrado en el cuestionario:', err);
          setStatusMessage(
            '❌ El participante no está registrado en este evento.'
          );
        }
      } else {
        setStatusMessage('⚠️ El QR no contiene los campos requeridos');
      }
    } catch (err) {
      console.error('QR malformado:', err);
      setStatusMessage('❌ Error al leer el QR: formato inválido');
    }
  };

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

    try {
      const response = await axiosInstance.post(
        `/participante-evento/asistencia/${scannedData.id_participante}/${scannedData.id_cuestionario}`
      );

      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);
    setScannedData(null);
  };

  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>

                  <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);
          setScannedData(null);
        }}
        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">
          {scannedData ? (
            <>
              <div className="mb-4">
                <div className="mb-3">
                  <i
                    className="bi bi-person-check-fill text-success"
                    style={{ fontSize: '3rem' }}
                  ></i>
                </div>
                <h5 className="mb-3 fw-semibold">
                  Información del participante
                </h5>
                <div className="card bg-light border-0 rounded-3">
                  <div className="card-body py-3">
                    <div className="d-flex align-items-center justify-content-center">
                      <i className="bi bi-envelope-fill text-primary me-2"></i>
                      <strong className="me-2">Correo:</strong>
                      <span className="text-primary fw-medium">
                        {participante}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <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);
                    setScannedData(null);
                  }}
                  className="px-4 py-2 rounded-pill"
                >
                  <i className="bi bi-x-lg me-2"></i>
                  Cancelar
                </Button>
              </div>
            </>
          ) : (
            <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">QR inválido o malformado</h6>
            </div>
          )}
        </div>
      </Modal>
    </main>
  );
}
