import React, { useState, useEffect, memo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Typography } 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 url = "http://localhost:9531/qrview";

    const handleReset = async() => {
        setIsPlaying(false);
        await resetWA();
        setIsPlaying(true);
    };

    useEffect(() => {
        const token = localStorage.getItem('token');

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

    return (
        <div style={{ padding: '20px' }}>

            <div style={{ marginBottom: 20 }}>
                <Button type="primary" onClick={handleReset} style={{ marginRight: 10 }}>
                    <ReloadOutlined/> Restart WhatsApp
                </Button>
            </div>

            <div
                style={{
                    border: '1px solid #ddd',
                    height: '700px',
                    background: '#fafafa',
                }}
            >
                {isPlaying ? (
                    <iframe
                        src={url}
                        title="Web Preview"
                        style={{
                            width: '100%',
                            height: '100%',
                            border: 'none',
                        }}
                    />
                ) : (
                    <div
                        style={{
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                            height: '100%',
                            color: '#888',
                        }}
                    >
                        Memuat Halaman WhatsApp QR Code
                    </div>
                )}
            </div>
        </div>
    );
});

export default IndexWebControl;