import React, { useState, useEffect } from 'react';
import { useConvex } from 'convex/react';
import { api } from '../../../../convex/_generated/api';

const ChannelSettingsModal = ({ channel, onClose, onRename, onDelete }) => {
    const [name, setName] = useState(channel.name);
    const [activeTab, setActiveTab] = useState('Overview');

    const convex = useConvex();

    useEffect(() => {
        const handleKey = (e) => { if (e.key === 'Escape') onClose(); };
        window.addEventListener('keydown', handleKey);
        return () => window.removeEventListener('keydown', handleKey);
    }, [onClose]);

    const handleSave = async () => {
        try {
            await convex.mutation(api.channels.rename, { id: channel._id, name });
            onRename(channel._id, name);
            onClose();
        } catch (err) {
            console.error(err);
            alert('Failed to update channel: ' + err.message);
        }
    };

    const handleDelete = async () => {
        if (!confirm('Are you sure you want to delete this channel? This cannot be undone.')) return;

        try {
            await convex.mutation(api.channels.remove, { id: channel._id });
            onDelete(channel._id);
            onClose();
        } catch (err) {
            console.error(err);
            alert('Failed to delete channel: ' + err.message);
        }
    };

    return (
        <div style={{
            position: 'fixed',
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: 'var(--bg-primary)',
            zIndex: 1000,
            display: 'flex',
            color: 'var(--text-normal)'
        }}>
            {/* Sidebar */}
            <div style={{
                width: '218px',
                backgroundColor: 'var(--bg-secondary)',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'flex-end',
                padding: '60px 6px 60px 20px'
            }}>
                <div style={{ width: '100%', padding: '0 10px' }}>
                    <div style={{
                        fontSize: '12px',
                        fontWeight: '700',
                        color: 'var(--text-muted)',
                        marginBottom: '6px',
                        textTransform: 'uppercase'
                    }}>
                        {channel.name} Text Channels
                    </div>

                    <div
                        onClick={() => setActiveTab('Overview')}
                        style={{
                            padding: '6px 10px',
                            borderRadius: '4px',
                            backgroundColor: activeTab === 'Overview' ? 'var(--background-modifier-selected)' : 'transparent',
                            color: activeTab === 'Overview' ? 'var(--header-primary)' : 'var(--header-secondary)',
                            cursor: 'pointer',
                            marginBottom: '2px',
                            fontSize: '15px'
                        }}
                    >
                        Overview
                    </div>

                    <div style={{ height: '1px', backgroundColor: 'var(--border-subtle)', margin: '8px 0' }} />

                    <div
                        onClick={() => setActiveTab('Delete')}
                        style={{
                            padding: '6px 10px',
                            borderRadius: '4px',
                            color: '#ed4245',
                            cursor: 'pointer',
                            fontSize: '15px',
                            display: 'flex',
                            justifyContent: 'space-between'
                        }}
                    >
                        Delete Channel
                        <span>🗑️</span>
                    </div>
                </div>
            </div>

            {/* Content */}
            <div style={{ flex: 1, display: 'flex', justifyContent: 'flex-start', overflowY: 'auto' }}>
                <div style={{ flex: 1, maxWidth: '740px', padding: '60px 40px 80px', position: 'relative' }}>
                    <h2 style={{ color: 'var(--header-primary)', margin: 0, marginBottom: '20px' }}>
                        {activeTab === 'Delete' ? 'Delete Channel' : 'Overview'}
                    </h2>

                {activeTab === 'Overview' && (
                    <>
                        <div style={{ marginBottom: '20px' }}>
                            <label style={{
                                display: 'block',
                                color: 'var(--header-secondary)',
                                fontSize: '12px',
                                fontWeight: '700',
                                textTransform: 'uppercase',
                                marginBottom: '8px'
                            }}>
                                Channel Name
                            </label>
                            <input
                                type="text"
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                                style={{
                                    width: '100%',
                                    backgroundColor: 'var(--bg-tertiary)',
                                    border: 'none',
                                    borderRadius: '4px',
                                    padding: '10px',
                                    color: 'var(--text-normal)',
                                    fontSize: '16px',
                                    outline: 'none'
                                }}
                            />
                        </div>

                        <div style={{ display: 'flex', gap: '20px' }}>
                            <button
                                onClick={handleSave}
                                style={{
                                    backgroundColor: '#3ba55c',
                                    color: 'var(--header-primary)',
                                    border: 'none',
                                    borderRadius: '4px',
                                    padding: '10px 24px',
                                    cursor: 'pointer',
                                    fontSize: '14px',
                                    fontWeight: '500'
                                }}
                            >
                                Save Changes
                            </button>
                        </div>
                    </>
                )}

                {activeTab === 'Delete' && (
                    <div style={{ backgroundColor: 'var(--bg-tertiary)', padding: '16px', borderRadius: '8px', border: '1px solid #ed4245' }}>
                         <h3 style={{ color: 'var(--header-primary)', marginTop: 0 }}>Are you sure?</h3>
                         <p style={{ color: 'var(--header-secondary)' }}>
                             Deleting <b>#{channel.name}</b> cannot be undone. All messages and keys will be lost forever.
                         </p>
                         <button
                            onClick={handleDelete}
                            style={{
                                backgroundColor: '#ed4245',
                                color: 'var(--header-primary)',
                                border: 'none',
                                borderRadius: '4px',
                                padding: '10px 24px',
                                cursor: 'pointer',
                                fontSize: '14px',
                                fontWeight: '500'
                            }}
                        >
                            Delete Channel
                        </button>
                    </div>
                )}

                </div>
                <div style={{ flex: '0 0 36px', paddingTop: '60px', marginLeft: '8px' }}>
                    <button
                        onClick={onClose}
                        style={{
                            width: '36px', height: '36px', borderRadius: '50%',
                            border: '2px solid var(--header-secondary)', background: 'transparent',
                            color: 'var(--header-secondary)', cursor: 'pointer',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            fontSize: '18px',
                        }}
                    >
                        ✕
                    </button>
                    <div style={{ fontSize: '13px', fontWeight: '600', color: 'var(--header-secondary)', textAlign: 'center', marginTop: '4px' }}>
                        ESC
                    </div>
                </div>
                <div style={{ flex: '0.5' }} />
            </div>
        </div>
    );
};

export default ChannelSettingsModal;
