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

const { Text } = Typography;

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

    const [isPlaying, setIsPlaying] = useState(true);

    const url = import.meta.env.VITE_WHATSAPP_URL;

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

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

        if (token) {
            setBreadcrumbItems([
                {
                    title: (
                        <Text strong style={{ fontSize: '14px' }}>
                            • WhatsApp 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="WhatsApp 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 IndexWhatsAppControl;
