import React, { useState, useEffect } from 'react';
import { getNonce, isPro } from '../../Helpers';
import NoticeModal from '../NoticeModal/NoticeModal';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/Delete';
import PollIcon from '@mui/icons-material/Poll';
import VisibilityIcon from '@mui/icons-material/Visibility';
import BarChartIcon from '@mui/icons-material/BarChart';
import LockIcon from '@mui/icons-material/Lock';

// Declare wp global for WordPress
declare const wp: any;

interface Poll {
    id: number;
    poll_name: string;
    description: string;
    featured_image: string;
    initial_form_id: number | null;
    answers: any[];
    settings: any;
    created_at: string;
    updated_at: string;
}

interface PollListProps {
    onCreatePoll: () => void;
    onEditPoll: (poll: Poll) => void;
    onViewResults: (poll: Poll) => void;
}

const PollList: React.FC<PollListProps> = ({ onCreatePoll, onEditPoll, onViewResults }) => {
    const [polls, setPolls] = useState<Poll[]>([]);
    const [loading, setLoading] = useState(true);
    const [deleting, setDeleting] = useState<number | null>(null);
    const [isProUser, setIsProUser] = useState(false);
    const [previewUrl, setPreviewUrl] = useState<string | null>(null);

    const [modalConfig, setModalConfig] = useState({
        isOpen: false,
        type: 'confirmation',
        title: '',
        message: '',
        onConfirm: () => { },
        confirmText: 'Confirm',
        declineText: 'Cancel',
        mode: 'success',
        position: 'center' as 'center' | 'top-right'
    });

    const closeModal = () => {
        setModalConfig(prev => ({ ...prev, isOpen: false }));
    };

    useEffect(() => {
        loadPolls();
        checkProStatus();
    }, []);

    const checkProStatus = () => {
        const isProuser = isPro();
        setIsProUser(isProuser);
    };

    const showProModal = () => {
        setModalConfig({
            isOpen: true,
            type: 'premium',
            title: '🚀 Upgrade to Pro',
            message: 'Create unlimited polls with Pro! Free version is limited to 1 poll. Upgrade now to unlock unlimited polls and advanced features!',
            mode: 'success',
            onConfirm: () => {
                window.open('https://wpazleen.com/simple-form-pricing/', '_blank');
                closeModal();
            },
            confirmText: 'Upgrade Now',
            declineText: 'Maybe Later',
            position: 'center'
        });
    };

    const handleCreatePoll = () => {
        if (!isProUser && polls.length >= 1) {
            showProModal();
            return;
        }
        onCreatePoll();
    };

    const loadPolls = () => {
        setLoading(true);
        (wp as any).ajax.send('simpleform_get_polls', {
            data: {
                nonce: getNonce(),
            },
            success(response: any) {
                if (response.polls) {
                    setPolls(response.polls);
                }
                setLoading(false);
            },
            error(error: any) {
                console.error('Error loading polls:', error);
                setLoading(false);
            },
        });
    };

    const handleDelete = (poll: Poll) => {
        setModalConfig({
            isOpen: true,
            type: 'confirmation',
            title: 'Delete Poll',
            message: `Are you sure you want to delete "${poll.poll_name}"? This action cannot be undone.`,
            mode: 'warning',
            onConfirm: () => {
                setDeleting(poll.id);
                (wp as any).ajax.send('simpleform_delete_poll', {
                    data: {
                        nonce: getNonce(),
                        poll_id: poll.id,
                    },
                    success(response: any) {
                        setPolls(prev => prev.filter(p => p.id !== poll.id));
                        setDeleting(null);

                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Success',
                            message: `Poll "${poll.poll_name}" deleted successfully`,
                            position: 'top-right',
                            mode: 'success',
                            onConfirm: () => {},
                            confirmText: 'OK',
                            declineText: 'Cancel',
                        });
                        setTimeout(closeModal, 3000);
                    },
                    error(error: any) {
                        console.error('Error deleting poll:', error);
                        setDeleting(null);

                        setModalConfig({
                            isOpen: true,
                            type: 'toast',
                            title: 'Error',
                            message: 'Failed to delete poll. Please try again.',
                            position: 'top-right',
                            mode: 'error',
                            onConfirm: () => {},
                            confirmText: 'OK',
                            declineText: 'Cancel',
                        });
                        setTimeout(closeModal, 3000);
                    },
                });
                closeModal();
            },
            confirmText: 'Yes, Delete',
            declineText: 'Cancel',
            position: 'center'
        });
    };

    const handlePreview = (poll: Poll) => {
        (wp as any).ajax.send('simpleform_get_poll_preview_url', {
            data: {
                nonce: getNonce(),
                poll_id: poll.id,
            },
            success(response: any) {
                if (response.preview_url) {
                    setPreviewUrl(response.preview_url);
                }
            },
            error(error: any) {
                console.error('Error getting preview URL:', error);
                setModalConfig({
                    isOpen: true,
                    type: 'toast',
                    title: 'Error',
                    message: 'Failed to generate preview URL.',
                    position: 'top-right',
                    mode: 'error',
                    onConfirm: () => {},
                    confirmText: 'OK',
                    declineText: 'Cancel',
                });
                setTimeout(closeModal, 3000);
            },
        });
    };

    const closePreview = () => {
        setPreviewUrl(null);
    };

    const formatDate = (dateString: string) => {
        return new Date(dateString).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'short',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    };

    if (loading) {
        return (
            <div className="poll-loading">
                <div className="spinner"></div>
                <p>Loading polls...</p>
            </div>
        );
    }

    return (
        <div className="poll-list-container">
            <div className="poll-list-header">
                <div className="header-content">
                    <h1>
                        <PollIcon />
                        Polls
                    </h1>
                    <p>Create interactive polls to gather opinions and feedback from your audience</p>
                </div>
                <button
                    className={`create-poll-btn ${!isProUser && polls.length >= 1 ? 'pro-locked-btn' : ''}`}
                    onClick={handleCreatePoll}
                >
                    <AddIcon />
                    Create Poll
                    {!isProUser && polls.length >= 1 && <LockIcon style={{ marginLeft: '8px', fontSize: '18px' }} />}
                </button>
            </div>

            {polls.length === 0 ? (
                <div className="no-polls">
                    <div className="no-polls-content">
                        <PollIcon className="no-polls-icon" />
                        <h3>No polls yet</h3>
                        <p>Create your first poll to start gathering feedback</p>
                        <button className="create-first-poll-btn" onClick={onCreatePoll}>
                            <AddIcon />
                            Create Your First Poll
                        </button>
                    </div>
                </div>
            ) : (
                <div className="poll-grid">
                    {polls.map(poll => (
                        <div key={poll.id} className="poll-card">
                            {poll.featured_image && (
                                <div className="poll-featured-image">
                                    <img src={poll.featured_image} alt={poll.poll_name} />
                                </div>
                            )}

                            <div className="poll-card-header">
                                <div className="poll-icon">
                                    <PollIcon />
                                </div>
                                <div className="poll-info">
                                    <h3>{poll.poll_name}</h3>
                                    <p className="poll-description">
                                        {poll.description || 'No description'}
                                    </p>
                                </div>
                            </div>

                            <div className="poll-stats">
                                <div className="stat">
                                    <span className="stat-label">Answers:</span>
                                    <span className="stat-value">{poll.answers?.length || 0}</span>
                                </div>
                                <div className="stat">
                                    <span className="stat-label">Type:</span>
                                    <span className="stat-value">
                                        {poll.settings?.allow_multiple ? 'Multiple Choice' : 'Single Choice'}
                                    </span>
                                </div>
                                <div className="stat">
                                    <span className="stat-label">Created:</span>
                                    <span className="stat-value">{formatDate(poll.created_at)}</span>
                                </div>
                            </div>

                            <div className="poll-actions">
                                <button
                                    className="action-btn edit-btn"
                                    onClick={() => onEditPoll(poll)}
                                    title="Edit Poll"
                                >
                                    <EditIcon />
                                </button>
                                <button
                                    className="action-btn results-btn"
                                    onClick={() => onViewResults(poll)}
                                    title="View Results"
                                >
                                    <BarChartIcon />
                                </button>
                                <button
                                    className="action-btn preview-btn"
                                    onClick={() => handlePreview(poll)}
                                    title="Preview Poll"
                                >
                                    <VisibilityIcon />
                                </button>
                                <button
                                    className="action-btn delete-btn"
                                    onClick={() => handleDelete(poll)}
                                    disabled={deleting === poll.id}
                                    title="Delete Poll"
                                >
                                    {deleting === poll.id ? (
                                        <div className="mini-spinner"></div>
                                    ) : (
                                        <DeleteIcon />
                                    )}
                                </button>
                            </div>

                            <div className="poll-shortcode">
                                <label>Shortcode:</label>
                                <code>[simple_poll id="{poll.id}"]</code>
                                <button
                                    className="copy-shortcode-btn"
                                    onClick={() => {
                                        navigator.clipboard.writeText(`[simple_poll id="${poll.id}"]`);
                                    }}
                                    title="Copy shortcode"
                                >
                                    Copy
                                </button>
                            </div>
                        </div>
                    ))}
                </div>
            )}

            <NoticeModal
                isOpen={modalConfig.isOpen}
                onClose={closeModal}
                onConfirm={modalConfig.onConfirm}
                onDecline={closeModal}
                type={modalConfig.type}
                mode={modalConfig.mode}
                title={modalConfig.title}
                message={modalConfig.message}
                confirmText={modalConfig.confirmText}
                declineText={modalConfig.declineText}
                position={modalConfig.position || 'center'}
                autoClose={modalConfig.type === 'toast'}
                autoCloseTime={3000}
            />

            {previewUrl && (
                <div className="preview-modal-overlay" onClick={closePreview}>
                    <div className="preview-modal-container" onClick={(e) => e.stopPropagation()}>
                        <div className="preview-modal-header">
                            <h2>Poll Preview</h2>
                            <button className="preview-modal-close" onClick={closePreview}>×</button>
                        </div>
                        <div className="preview-modal-body">
                            <iframe
                                src={previewUrl}
                                title="Poll Preview"
                                className="preview-iframe"
                            />
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default PollList;
