import React, { useState, useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import { useDispatch, useSelector } from 'react-redux';
import { fetchLicenseInfo, activateLicense, removeLicense, checkLicenseUpdate, clearError, clearSuccess } from '../store/licenseSlice';

const S = {
    orange: '#ED7D31', orangeDk: '#D46A1E', orangeLt: '#FEF0E6',
    teal: '#39758D', tealLt: '#EBF1F4',
    bg: '#F4F6F8', white: '#FFFFFF', border: '#E2E8F0',
    text: '#1A202C', muted: '#64748B', light: '#94A3B8',
    success: '#10B981', danger: '#EF4444',
    shadow: '0 1px 3px rgba(0,0,0,.07), 0 1px 2px rgba(0,0,0,.05)',
    radius: 12, radiusSm: 6,
};

function Btn({ children, variant = 'primary', loading, style, disabled, ...props }) {
    const base = {
        display: 'inline-flex', alignItems: 'center', gap: 6,
        height: 34, padding: '0 14px', borderRadius: S.radiusSm,
        fontSize: 13, fontWeight: 500, cursor: disabled || loading ? 'not-allowed' : 'pointer',
        border: 'none', transition: 'background .15s', fontFamily: 'inherit',
        opacity: disabled || loading ? 0.6 : 1,
    };
    const variants = {
        primary: { background: S.orange, color: '#fff' },
        secondary: { background: S.tealLt, color: S.teal },
        ghost: { background: '#F1F5F9', color: S.muted },
    };
    return (
        <button style={{ ...base, ...variants[variant], ...style }} disabled={disabled || loading} {...props}>
            {loading && <Spinner />}
            {children}
        </button>
    );
}

function Spinner() {
    return (
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ animation: 'spin 1s linear infinite' }}>
            <style>{`@keyframes spin { to { transform: rotate(360deg) } }`}</style>
            <circle cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="3" opacity="0.25" />
            <path d="M12 2a10 10 0 0 1 10 10" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
        </svg>
    );
}

function ReadonlyField({ children, mono }) {
    return (
        <div style={{
            height: 34, padding: '0 10px', display: 'flex', alignItems: 'center',
            background: '#F8FAFC', border: `1px solid ${S.border}`,
            borderRadius: S.radiusSm, fontSize: 13,
            fontFamily: mono ? "'Courier New', monospace" : 'inherit',
            color: mono ? S.teal : S.text,
        }}>
            {children}
        </div>
    );
}

function KeyIcon() {
    return (
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0 3 3L22 7l-3-3m-3.5 3.5L19 4" />
        </svg>
    );
}

function BadgeIcon() {
    return (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <rect x="2" y="7" width="20" height="14" rx="2" />
            <path d="M16 7V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2" />
            <line x1="12" y1="12" x2="12" y2="16" />
            <circle cx="12" cy="12" r="1" fill="currentColor" />
        </svg>
    );
}

function InfoIcon() {
    return (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="12" cy="12" r="10" />
            <line x1="12" y1="16" x2="12" y2="12" />
            <line x1="12" y1="8" x2="12.01" y2="8" />
        </svg>
    );
}

function CheckCircleIcon() {
    return (
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={S.success} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
            <polyline points="22 4 12 14.01 9 11.01" />
        </svg>
    );
}

const cardStyle = {
    background: S.white,
    border: `1px solid ${S.border}`,
    borderRadius: S.radius,
    padding: 24,
    boxShadow: S.shadow,
};

const cardTitleStyle = {
    fontSize: 14,
    fontWeight: 600,
    color: S.text,
    marginBottom: 16,
    display: 'flex',
    alignItems: 'center',
    gap: 8,
};

const labelStyle = {
    fontSize: 12,
    fontWeight: 600,
    color: S.text,
    letterSpacing: '0.1px',
    marginBottom: 5,
    display: 'block',
};

function maskKey(key) {
    if (!key || key.length <= 9) return key;
    return key.slice(0, 4) + '•'.repeat(key.length - 9) + key.slice(-5);
}

function formatDate(dateStr) {
    if (!dateStr) return '—';
    const d = new Date(dateStr);
    if (isNaN(d.getTime())) return dateStr;
    return d.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
}

function isExpired(dateStr) {
    if (!dateStr) return false;
    const d = new Date(dateStr);
    return !isNaN(d.getTime()) && d < new Date();
}

function notify(type, message) {
    window.lazytasksShowNotification?.({
        type,
        message,
        duration: 4000,
    });
}

export default function LicenseTabV3() {
    const dispatch = useDispatch();
    const {
        licenseKey, isActive, expireDate, isPremiumInstalled, siteUrl,
        isLoading, isActivating, isDeactivating, isChecking,
        error, successMessage,
    } = useSelector((state) => state.settings.license);

    const [licenseKeyVisible, setLicenseKeyVisible] = useState(false);
    const [newLicenseKey, setNewLicenseKey] = useState('');

    useEffect(() => {
        dispatch(fetchLicenseInfo());
    }, [dispatch]);

    useEffect(() => {
        if (successMessage) {
            notify('success', successMessage);
            dispatch(clearSuccess());
        }
    }, [successMessage, dispatch]);

    useEffect(() => {
        if (error) {
            notify('error', error);
            dispatch(clearError());
        }
    }, [error, dispatch]);

    const handleActivate = () => {
        if (!newLicenseKey.trim()) return;
        dispatch(activateLicense({ license_key: newLicenseKey.trim(), domain: siteUrl }))
            .unwrap()
            .then(() => {
                setNewLicenseKey('');
                dispatch(fetchLicenseInfo());
            })
            .catch(() => {});
    };

    const handleDeactivate = () => {
        dispatch(removeLicense({ domain: siteUrl }));
    };

    const handleCheck = () => {
        dispatch(checkLicenseUpdate({ domain: siteUrl }));
    };

    const expired = isExpired(expireDate);
    const noPremium = !isPremiumInstalled;

    if (isLoading) {
        return (
            <div>
                <div style={{ marginBottom: 20 }}>
                    <div style={{ fontSize: 16, fontWeight: 700, color: S.text }}>{__('License', 'lazytasks-project-task-management')}</div>
                    <div style={{ fontSize: 12, color: S.muted, marginTop: 2 }}>{__('Manage your LazyTasks plugin license key.', 'lazytasks-project-task-management')}</div>
                </div>
                <div style={{ ...cardStyle, display: 'flex', alignItems: 'center', gap: 10, color: S.muted, fontSize: 13 }}>
                    <Spinner /> {__('Loading license information...', 'lazytasks-project-task-management')}
                </div>
            </div>
        );
    }

    return (
        <div>
            {/* Header */}
            <div style={{ marginBottom: 20, position: 'sticky', top: 0, zIndex: 10, background: '#F4F6F8', paddingTop: 4, paddingBottom: 4 }}>
                <div style={{ fontSize: 16, fontWeight: 700, color: S.text }}>{__('License', 'lazytasks-project-task-management')}</div>
                <div style={{ fontSize: 12, color: S.muted, marginTop: 2 }}>{__('Manage your LazyTasks plugin license key.', 'lazytasks-project-task-management')}</div>
            </div>

            {/* Status banner — adapts to premium/license state */}
            <div style={{
                ...cardStyle,
                background: noPremium ? S.orangeLt : isActive ? '#D1FAE540' : S.tealLt,
                border: `1px solid ${noPremium ? S.orange + '40' : isActive ? S.success + '40' : S.teal + '40'}`,
                display: 'flex',
                alignItems: 'flex-start',
                gap: 12,
                marginBottom: 16,
            }}>
                <span style={{ color: noPremium ? S.orange : isActive ? S.success : S.teal, flexShrink: 0, marginTop: 1 }}>
                    {isActive ? <CheckCircleIcon /> : <InfoIcon />}
                </span>
                <div>
                    {noPremium ? (
                        <>
                            <div style={{ fontSize: 13, fontWeight: 600, color: S.text, marginBottom: 4 }}>
                                {__( 'Mobile App Requires Premium Plugin', 'lazytasks-project-task-management' )}
                            </div>
                            <div style={{ fontSize: 12, color: S.muted, lineHeight: 1.5 }}>
                                {__( "Get the LazyTasks' Premium plugin by", 'lazytasks-project-task-management' )}{' '}
                                <a href="https://lazycoders.co/lazytasks/?product_name=lazy_task&plugin_slug=lazytasks-premium#buy-now" target="_blank" rel="noopener noreferrer" style={{ color: S.orange, fontWeight: 600, textDecoration: 'underline' }}>
                                    {__( 'clicking here', 'lazytasks-project-task-management' )}
                                </a>
                                {__( '; Install and activate to use our mobile app to connect with this installation and manage your projects on the go. Happy Tasking!', 'lazytasks-project-task-management' )}{' '}
                                <span role="img" aria-label="rocket">🚀</span>
                            </div>
                        </>
                    ) : !isActive ? (
                        <>
                            <div style={{ fontSize: 13, fontWeight: 600, color: S.text, marginBottom: 4 }}>
                                {__( 'License Required', 'lazytasks-project-task-management' )}
                            </div>
                            <div style={{ fontSize: 12, color: S.muted, lineHeight: 1.5 }}>
                                {__( 'Enter a valid license key to activate mobile access. Once done, click on the', 'lazytasks-project-task-management' )} <strong>"{__( 'Mobile App', 'lazytasks-project-task-management' )}"</strong> {__( 'button on the header to connect your mobile app.', 'lazytasks-project-task-management' )}
                            </div>
                        </>
                    ) : (
                        <>
                            <div style={{ fontSize: 13, fontWeight: 600, color: S.text, marginBottom: 4 }}>
                                {__( 'License Active', 'lazytasks-project-task-management' )}
                            </div>
                            <div style={{ fontSize: 12, color: S.muted, lineHeight: 1.5 }}>
                                {__( 'Thanks for choosing LazyTasks. Click on the', 'lazytasks-project-task-management' )} <strong>"{__( 'Mobile App', 'lazytasks-project-task-management' )}"</strong> {__( 'button on the header and follow instructions in order to connect your mobile app.', 'lazytasks-project-task-management' )}
                            </div>
                        </>
                    )}
                </div>
            </div>

            {/* Two-column layout */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, alignItems: 'start' }}>

                {/* LEFT — Enter / View License Key */}
                <div style={{
                    ...cardStyle,
                    ...(isActive || noPremium ? { opacity: 0.5, pointerEvents: 'none' } : {}),
                    ...(noPremium ? { filter: 'blur(2px)' } : {}),
                }}>
                    <div style={cardTitleStyle}>
                        <span style={{ color: S.teal, display: 'flex' }}><KeyIcon /></span>
                        {__( 'Enter a New License Key', 'lazytasks-project-task-management' )}
                        {isActive && (
                            <span style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 600, color: S.success }}>
                                <CheckCircleIcon /> {__( 'Licensed', 'lazytasks-project-task-management' )}
                            </span>
                        )}
                    </div>

                    <div style={{ marginBottom: 14 }}>
                        <label style={labelStyle}>{__('License Key', 'lazytasks-project-task-management')}</label>
                        {isActive ? (
                            /* Show current key read-only when licensed */
                            <div style={{
                                display: 'flex',
                                border: `1px solid ${S.border}`,
                                borderRadius: S.radiusSm,
                                overflow: 'hidden',
                            }}>
                                <div style={{
                                    display: 'flex', alignItems: 'center', padding: '0 10px',
                                    background: '#F8FAFC', borderRight: `1px solid ${S.border}`,
                                    color: S.muted,
                                }}>
                                    <KeyIcon />
                                </div>
                                <input
                                    type="text"
                                    value={maskKey(licenseKey)}
                                    readOnly
                                    style={{
                                        flex: 1, height: 34, padding: '0 10px',
                                        border: 'none', outline: 'none', fontSize: 13,
                                        fontFamily: 'inherit', color: S.text, background: '#F8FAFC',
                                        cursor: 'default',
                                    }}
                                />
                            </div>
                        ) : (
                            /* Editable input when no license */
                            <div style={{
                                display: 'flex',
                                border: `1px solid ${S.border}`,
                                borderRadius: S.radiusSm,
                                overflow: 'hidden',
                                transition: 'border-color .18s, box-shadow .18s',
                            }}
                                onFocus={e => {
                                    e.currentTarget.style.borderColor = S.teal;
                                    e.currentTarget.style.boxShadow = '0 0 0 3px rgba(57,117,141,.12)';
                                }}
                                onBlur={e => {
                                    e.currentTarget.style.borderColor = S.border;
                                    e.currentTarget.style.boxShadow = 'none';
                                }}
                            >
                                <input
                                    type="text"
                                    value={newLicenseKey}
                                    onChange={e => setNewLicenseKey(e.target.value)}
                                    placeholder={__( "Enter your license key", "lazytasks-project-task-management" )}
                                    onKeyDown={e => { if (e.key === 'Enter') handleActivate(); }}
                                    style={{
                                        flex: 1, height: 34, padding: '0 10px',
                                        border: 'none', outline: 'none', fontSize: 13,
                                        fontFamily: 'inherit', color: S.text, background: S.white,
                                    }}
                                />
                            </div>
                        )}
                        <div style={{ fontSize: 11, color: S.light, marginTop: 4 }}>
                            {__( 'Purchase a license at', 'lazytasks-project-task-management' )}{' '}
                            <span style={{ color: S.teal, textDecoration: 'underline', cursor: 'pointer' }}>
                                lazytasks.com/pricing
                            </span>
                        </div>
                    </div>

                    {!isActive && (
                        <Btn
                            variant="primary"
                            loading={isActivating}
                            disabled={!newLicenseKey.trim()}
                            onClick={handleActivate}
                        >
                            {__( 'Activate License', 'lazytasks-project-task-management' )}
                        </Btn>
                    )}
                </div>

                {/* RIGHT — Current License */}
                <div style={{
                    ...cardStyle,
                    ...(!isActive ? { opacity: 0.5, pointerEvents: 'none' } : {}),
                    ...(noPremium ? { filter: 'blur(2px)' } : {}),
                }}>
                    <div style={cardTitleStyle}>
                        <span style={{ color: S.teal, display: 'flex' }}><BadgeIcon /></span>
                        {__( 'Current License', 'lazytasks-project-task-management' )}
                    </div>

                    {/* 2-column info grid */}
                    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
                        <div>
                            <label style={labelStyle}>{__('License Type', 'lazytasks-project-task-management')}</label>
                            <ReadonlyField>
                                <span style={{
                                    background: isActive ? '#D1FAE5' : '#F1F5F9',
                                    color: isActive ? '#065F46' : S.light,
                                    fontSize: 11, fontWeight: 700,
                                    padding: '2px 8px', borderRadius: 20, marginRight: 8,
                                }}>
                                    {__( 'PRO', 'lazytasks-project-task-management' )}
                                </span>
                                {isActive ? __( 'Professional Plan', 'lazytasks-project-task-management' ) : '—'}
                            </ReadonlyField>
                        </div>

                        <div>
                            <label style={labelStyle}>{__('Status', 'lazytasks-project-task-management')}</label>
                            <ReadonlyField>
                                <span style={{
                                    width: 8, height: 8, borderRadius: '50%',
                                    background: !isActive ? S.light : expired ? S.danger : S.success,
                                    flexShrink: 0, marginRight: 6,
                                    display: 'inline-block',
                                }} />
                                {!isActive
                                    ? '—'
                                    : expired
                                        ? __('Expired', 'lazytasks-project-task-management')
                                        : __('Active', 'lazytasks-project-task-management')}
                            </ReadonlyField>
                        </div>

                        <div>
                            <label style={labelStyle}>{__('Registered Domain', 'lazytasks-project-task-management')}</label>
                            <ReadonlyField mono>
                                {isActive && siteUrl ? new URL(siteUrl).hostname : '—'}
                            </ReadonlyField>
                        </div>

                        <div>
                            <label style={labelStyle}>{__('Expires', 'lazytasks-project-task-management')}</label>
                            <ReadonlyField>
                                <span style={{ color: isActive && expired ? S.danger : S.text }}>
                                    {isActive ? formatDate(expireDate) : '—'}
                                </span>
                            </ReadonlyField>
                        </div>
                    </div>

                    {/* License key field */}
                    <div style={{ marginBottom: 16 }}>
                        <label style={labelStyle}>{__('License Key', 'lazytasks-project-task-management')}</label>
                        <div style={{
                            display: 'flex',
                            border: `1px solid ${S.border}`,
                            borderRadius: S.radiusSm,
                            overflow: 'hidden',
                        }}>
                            <div style={{
                                display: 'flex', alignItems: 'center', padding: '0 10px',
                                background: '#F8FAFC', borderRight: `1px solid ${S.border}`,
                                color: S.muted,
                            }}>
                                <KeyIcon />
                            </div>
                            <input
                                type="text"
                                value={isActive ? (licenseKeyVisible ? licenseKey : maskKey(licenseKey)) : ''}
                                readOnly
                                placeholder="—"
                                style={{
                                    flex: 1, height: 34, padding: '0 10px',
                                    border: 'none', outline: 'none', fontSize: 13,
                                    fontFamily: 'inherit', color: S.text, background: S.white,
                                    cursor: 'default',
                                }}
                            />
                            {isActive && (
                                <button
                                    onClick={() => setLicenseKeyVisible(v => !v)}
                                    title={licenseKeyVisible ? __('Hide', 'lazytasks-project-task-management') : __('Show', 'lazytasks-project-task-management')}
                                    style={{
                                        padding: '0 10px', background: '#F8FAFC',
                                        borderLeft: `1px solid ${S.border}`, border: 'none',
                                        cursor: 'pointer', color: S.muted, fontSize: 11,
                                    }}
                                >
                                    {licenseKeyVisible ? __('Hide', 'lazytasks-project-task-management') : __('Show', 'lazytasks-project-task-management')}
                                </button>
                            )}
                        </div>
                    </div>

                    {/* Actions */}
                    <div style={{ display: 'flex', gap: 8 }}>
                        <Btn variant="secondary" loading={isDeactivating} onClick={handleDeactivate}>
                            {__( 'Deactivate License', 'lazytasks-project-task-management' )}
                        </Btn>
                        <Btn variant="ghost" loading={isChecking} onClick={handleCheck}>
                            {__( 'Check for Updates', 'lazytasks-project-task-management' )}
                        </Btn>
                    </div>
                </div>
            </div>
        </div>
    );
}
