import React, { useState, useEffect, useRef, memo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Typography, message } from 'antd';
import { resetWA } from '../../api/web-control';
import { useBreadcrumb } from '../../layout/LayoutBreadcrumb';
import { ReloadOutlined } from '@ant-design/icons';

const { Text } = Typography;

const IndexWebControl = memo(function IndexWebControl() {
    const navigate = useNavigate();
    const { setBreadcrumbItems } = useBreadcrumb();

    const [isPlaying, setIsPlaying] = useState(true);
    const [currentUrl, setCurrentUrl] = useState('http://localhost:9531');
    const iframeRef = useRef(null);

    const handleReset = async () => {
        setIsPlaying(false);
        await resetWA();
        setIsPlaying(true);
        // Kembali ke halaman login setelah reset
        setCurrentUrl('https://localhost:9531');
        message.success('WhatsApp berhasil di-restart');
    };

    // Fungsi untuk redirect ke QR View
    const redirectToQRView = () => {
        setCurrentUrl('https://localhost:9531/qrview');
        message.info('Redirecting to QR View...');
    };

    // Fungsi untuk kembali ke login
    const backToLogin = () => {
        setCurrentUrl('https://localhost:9531');
        message.info('Back to login page');
    };

    useEffect(() => {
        const token = localStorage.getItem('token');
        if (token) {
            setBreadcrumbItems([
                {
                    title: (
                        <Text strong style={{ fontSize: '14px' }}>
                            • Web Control Panel
                        </Text>
                    ),
                },
            ]);
        } else {
            navigate('/signin');
        }
    }, [navigate, setBreadcrumbItems]);

    // Mendengarkan pesan dari iframe
    useEffect(() => {
        const handleMessage = (event) => {
            // Terima pesan dari domain manapun untuk testing
            console.log('Message received from:', event.origin);
            console.log('Message data:', event.data);

            // Cek apakah ini pesan login success
            if (event.data) {
                // Jika pesan adalah string
                if (typeof event.data === 'string') {
                    const lowerData = event.data.toLowerCase();
                    if (
                        lowerData.includes('login') ||
                        lowerData.includes('success') ||
                        lowerData.includes('authenticated') ||
                        lowerData.includes('qrview')
                    ) {
                        console.log('Login detected via string message');
                        redirectToQRView();
                    }
                }

                // Jika pesan adalah object
                if (typeof event.data === 'object') {
                    if (
                        event.data.type === 'LOGIN_SUCCESS' ||
                        event.data.status === 'success' ||
                        event.data.logged_in === true ||
                        event.data.redirect === true
                    ) {
                        console.log('Login detected via object message');
                        redirectToQRView();
                    }
                }
            }
        };

        window.addEventListener('message', handleMessage);

        return () => {
            window.removeEventListener('message', handleMessage);
        };
    }, []);

    // Alternative: Coba dengan timer (jika postMessage tidak berfungsi)
    useEffect(() => {
        // Jika tidak ada pesan dari iframe, coba redirect otomatis setelah 10 detik
        // Asumsi: login biasanya selesai dalam 10 detik
        const timer = setTimeout(() => {
            if (currentUrl === 'https://localhost:9531') {
                console.log('Auto redirect after 10 seconds (fallback)');
                redirectToQRView();
            }
        }, 10000);

        return () => clearTimeout(timer);
    }, [currentUrl]);

    return (
        <div style={{ padding: '20px' }}>
            <div style={{ marginBottom: 20, display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
                <Button type="primary" onClick={handleReset}>
                    <ReloadOutlined /> Restart WhatsApp
                </Button>
                {/* <Button onClick={redirectToQRView} type="default">
                    Redirect ke QR View
                </Button>
                <Button onClick={backToLogin} type="default">
                    Kembali ke Login
                </Button> */}
            </div>

            <div
                style={{
                    border: '1px solid #ddd',
                    height: '700px',
                    background: '#fafafa',
                    position: 'relative',
                }}
            >
                {isPlaying ? (
                    <iframe
                        key={currentUrl} // Force re-render saat URL berubah
                        ref={iframeRef}
                        src={currentUrl}
                        title="Web Preview"
                        style={{
                            width: '100%',
                            height: '100%',
                            border: 'none',
                        }}
                        onLoad={() => {
                            console.log('Iframe loaded with URL:', currentUrl);
                            // Hanya log, tidak mencoba mengakses URL untuk menghindari error CORS
                        }}
                        onError={(e) => console.error('Iframe error:', e)}
                    />
                ) : (
                    <div
                        style={{
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            height: '100%',
                            color: '#888',
                        }}
                    >
                        Memuat Halaman WhatsApp QR Code
                    </div>
                )}
            </div>
        </div>
    );
});

export default IndexWebControl;
