'use client';

import { Button } from '@/components/ui/button';
import AppLayout from '@/layouts/app-layout';
import { Head } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import { toast } from 'sonner';

import { BrowserQRCodeReader, IScannerControls, Result } from '@zxing/browser';
import axios from 'axios';

const qrCodeReader = new BrowserQRCodeReader();

interface ScanKehadiranProps {}

export default function ScanKehadiran({}: ScanKehadiranProps) {
    const [scanResult, setScanResult] = useState<string | null>(null);
    const [scanStatus, setScanStatus] = useState<string>('Memulai kamera...');
    const videoRef = useRef<HTMLVideoElement>(null);
    const scannerControls = useRef<IScannerControls | null>(null);

    const [processing, setProcessing] = useState<boolean>(false);

    // Tambahkan useRef untuk elemen audio
    const audioRef = useRef<HTMLAudioElement | null>(null);

    // Fungsi untuk memutar suara
    const playSuccessSound = () => {
        if (audioRef.current) {
            audioRef.current.currentTime = 0; // Reset audio ke awal
            audioRef.current.play().catch((e) => console.error('Error playing sound:', e));
        }
    };

    const startScanning = () => {
        if (!videoRef.current) {
            console.error('Error: Video element not found. Cannot start scanner.');
            setScanStatus('Error: Elemen kamera tidak ditemukan.');
            toast.error('Elemen kamera tidak ditemukan. Mohon refresh halaman.');
            return;
        }

        setScanStatus('Arahkan kamera ke QR Code...');
        setScanResult(null); // Reset scan result saat memulai ulang
        setProcessing(false); // Pastikan processing reset

        if (scannerControls.current) {
            scannerControls.current.stop();
            scannerControls.current = null;
        }

        qrCodeReader
            .decodeFromVideoDevice(undefined, videoRef.current, (result: Result | undefined, error: Error | undefined) => {
                if (result) {
                    handleScanSuccess(result.getText());
                    // Hentikan scanner setelah berhasil scan
                    if (scannerControls.current) {
                        scannerControls.current.stop();
                        scannerControls.current = null;
                    }
                } else if (error) {
                    // Hindari logging error "NotFoundException" yang normal saat tidak ada QR
                    if (!error.name?.startsWith('NotFoundException')) {
                        console.error('Error during scan:', error);
                        setScanStatus(`Kesalahan pemindaian: ${error.message}`);
                        toast.error(`Kesalahan pemindaian: ${error.message}`);
                    }
                }
            })
            .then((controls: IScannerControls) => {
                scannerControls.current = controls;
                console.log('QR Code reader started successfully.');
                setScanStatus('Kamera aktif, siap memindai.');
            })
            .catch((err) => {
                console.error('Error accessing camera or setting up QR reader:', err);
                setScanStatus('Gagal mengakses kamera atau terjadi kesalahan. Pastikan Anda memberikan izin akses kamera.');
                toast.error('Gagal memulai kamera. Pastikan Anda memberikan izin akses kamera.');
            });
    };

    useEffect(() => {
        // Inisialisasi elemen audio saat komponen di-mount
        // Pastikan jalur file suara Anda benar!
        audioRef.current = new Audio('/sounds/bp.mp3');

        startScanning();

        return () => {
            if (scannerControls.current) {
                scannerControls.current.stop();
                scannerControls.current = null;
            }
            qrCodeReader.reset();
            console.log('QR Code reader and camera stream stopped.');
        };
    }, []);

    const handleScanSuccess = (scannedData: string) => {
        setScanResult(scannedData);
        setScanStatus('QR Code terdeteksi. Memproses...');
        console.log('Scanned QR Code Data (raw):', scannedData);

        // --- Panggil fungsi untuk memutar suara di sini ---
        playSuccessSound();

        if (!scannedData || scannedData.trim() === '') {
            console.error('QR Code data is empty or invalid after scan. Not sending to backend.');
            setScanStatus('QR Code kosong atau tidak valid.');
            toast.error('QR Code kosong atau tidak valid. Pastikan QR Anda berisi UUID yang benar.');
            setTimeout(() => startScanning(), 2000);
            return;
        }

        setProcessing(true);

        axios
            .post(route('kehadiran.store'), {
                qr_code_data: scannedData,
            })
            .then((response) => {
                setProcessing(false);
                const dataReturned = response.data;

                if (response.status === 200 && dataReturned?.status === 'success') {
                    setScanStatus('Kehadiran berhasil dicatat!');
                    toast.success(dataReturned.message || 'Kehadiran berhasil dicatat!');
                } else {
                    setScanStatus(dataReturned?.message || 'Terjadi kesalahan yang tidak diketahui.');
                    toast.error(dataReturned?.message || 'Terjadi kesalahan yang tidak diketahui.');
                }
                setTimeout(() => startScanning(), 3000);
            })
            .catch((error) => {
                setProcessing(false);
                console.error('Axios Error (from direct POST):', error.response?.data || error.message);

                let displayMessage = 'Terjadi kesalahan saat memproses kehadiran. Silakan coba lagi.';
                if (error.response?.data?.message) {
                    displayMessage = error.response.data.message;
                } else if (error.response?.data?.errors?.qr_code_data) {
                    displayMessage = error.response.data.errors.qr_code_data[0];
                }

                setScanStatus(displayMessage);
                toast.error(displayMessage);

                setTimeout(() => startScanning(), 3000);
            });
    };

    return (
        <AppLayout header={<h2 className="text-xl leading-tight font-semibold text-gray-800">Scan Kehadiran</h2>}>
            <Head title="Scan Kehadiran" />

            <div className="py-12">
                <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
                    <div className="overflow-hidden rounded-lg bg-white p-6 shadow-xl lg:p-8">
                        <div className="flex flex-col items-center justify-center space-y-6">
                            <h2 className="text-2xl font-semibold text-gray-800">Scan QR Code untuk Kehadiran</h2>
                            <p className="text-center text-base text-gray-600">Arahkan kamera perangkat Anda ke QR Code kehadiran untuk mencatat.</p>

                            <div className="relative flex h-64 w-full max-w-sm items-center justify-center overflow-hidden rounded-lg border-2 border-dashed border-gray-300 bg-gray-100 text-lg text-gray-500">
                                <video ref={videoRef} id="video" className="h-full w-full object-cover" />
                                {(!videoRef.current || scanStatus.includes('Gagal mengakses kamera')) && (
                                    <div className="absolute inset-0 flex items-center justify-center rounded-lg bg-red-100 p-4 text-center text-sm text-red-700 opacity-75">
                                        {scanStatus}
                                    </div>
                                )}
                            </div>

                            <div className="mt-4 text-center">
                                <p className="text-lg font-medium text-gray-700">Status Pemindaian:</p>
                                <p className={`text-base font-semibold ${scanResult ? 'text-green-600' : 'text-gray-600'}`}>{scanStatus}</p>
                                {scanResult && <p className="mt-1 text-sm text-gray-500">Data Terdeteksi: {scanResult}</p>}
                            </div>

                            {processing && <p className="mt-2 text-blue-500">Sedang memproses...</p>}

                            {!processing && !scanStatus.includes('Kamera aktif') && (
                                <Button onClick={startScanning} className="mt-4">
                                    Mulai Ulang Pemindaian
                                </Button>
                            )}
                        </div>
                    </div>
                </div>
            </div>
            {/* Elemen audio tersembunyi */}
            <audio ref={audioRef} src="/sounds/bp.mp3" preload="auto" />
        </AppLayout>
    );
}
