"use client";

import { useState } from "react";
import { io, Socket } from "@/lib/zero-socket";

export default function QRScannerSimulation() {
  const [sessionId, setSessionId] = useState("");
  const [token, setToken] = useState("");
  const [status, setStatus] = useState("Waiting for Input");

  const handleScan = () => {
    setStatus("Scanning...");
    const socket: Socket = io(typeof window !== 'undefined' ? window.location.origin : '');

    socket.on("connect", () => {
       socket.emit("qr_auth_scan_success", { sessionId, token });
       setStatus("Success! Session authenticated.");
       setTimeout(() => {
          socket.disconnect();
       }, 1000);
    });

    socket.on("connect_error", () => {
       setStatus("Error connecting to Chat Server Socket.");
    });
  };

  return (
    <div className="min-h-screen bg-[#0a101d] text-white flex flex-col items-center justify-center p-8">
      <div className="bg-[#111827] p-8 rounded-2xl border border-gray-800 shadow-2xl max-w-md w-full">
        <h1 className="text-2xl font-bold mb-4 text-brand">📱 QR Scanner Simulation</h1>
        <p className="text-gray-400 text-sm mb-6">
          Masukkan Session ID yang muncul di layar IAM Desktop Anda, beserta Token Auth rahasia (contoh JWT) yang dimiliki perangkat mobile ini.
        </p>
        
        <input 
          type="text" 
          value={sessionId}
          onChange={(e) => setSessionId(e.target.value)}
          placeholder="Session ID (ex: 12345)"
          className="w-full bg-black/50 border border-white/10 p-3 rounded-lg mb-4 text-white"
        />
        <input 
          type="text" 
          value={token}
          onChange={(e) => setToken(e.target.value)}
          placeholder="JWT Token Rahasia dari HP"
          className="w-full bg-black/50 border border-white/10 p-3 rounded-lg mb-6 text-white"
        />

        <button 
          onClick={handleScan}
          className="w-full py-3 bg-brand text-black font-bold rounded-lg hover:opacity-80 transition-opacity">
          [SCAN] Otentikasi Jarak Jauh
        </button>

        <p className="mt-6 text-center text-xs font-mono text-gray-500">Status: {status}</p>
      </div>
    </div>
  );
}
