from dash import html, dcc
import dash_bootstrap_components as dbc
import base64

def user_login(user=None):
    """
    This function returns a login or logout section, depending on whether the user is logged in.
    It uses small card components with input fields or login status.
    """
    if user:
        login_card_header = html.Div([], className='card-header', style={'display': 'none'})
        login_card_body = html.Div([
            dbc.Row([
                dbc.Col([
                    html.Span(
                        f'Logged in as {user}',
                        className='text-dark',
                    )
                ], className='g-2', style={'maxWidth': '85%'})
            ], className='card-body pt-0 pb-1')
        ])
        login_card_footer = html.Div([
            html.Div([
                html.Button(
                    'Logout', id='logout-button',
                    className='mb-1 btn btn-sm btn-outline-light',
                    style={'width': '7rem'}
                ),
            ], className='bg-transparent d-flex')
        ], className='card-footer text-muted pt-1 pb-0')

        login_section = html.Div([
            login_card_header,
            login_card_body,
            login_card_footer
        ], className='card mb-3')

    else:
        login_card_header = html.Div([], className='card-header', style={'display': 'none'})
        login_card_body = html.Div([
            dbc.Row([
                dbc.Col(
                    dbc.Input(
                        id='login-email', type='email',
                        placeholder='Email', size='sm',
                        className='form-control text-light border-light',
                    ),
                    width=12, md=6
                ),
                dbc.Col(
                    dbc.Input(
                        id='login-password', type='password',
                        placeholder='Password', size='sm',
                        className='form-control text-light border-light',
                        style={'backgroundColor': 'transparent'}
                    ),
                    width=12, md=6
                ),
            ], className='g-2', style={'maxWidth': '85%'})
        ], className='card-body pt-2 pb-1')
        login_card_footer = html.Div([
            html.Div([
                html.Button(
                    'Login', id='login-button',
                    className='mb-1 btn btn-sm btn-outline-light',
                    style={'width': '7rem'}
                ),
            ], className='bg-transparent d-flex')
        ], className='card-footer text-muted pt-1 pb-0')

        login_section = html.Div([
            login_card_header,
            login_card_body,
            login_card_footer
        ], className='card mb-3')

    return login_section

def layout_account(users=None):
    """
    Renders a user list, if provided. Otherwise shows an empty div.
    """
    user_list = html.Ul([html.Li(u['email']) for u in users]) if users else html.Div()
    return html.Div([
        html.Br(),
        html.Br(),
        html.H5('User List'),
        html.Br(),
        user_list
    ])

def layout_registration():
    """
    A simple registration page with email and password fields.
    """
    return html.Div([
        html.Br(),
        html.Br(),
        html.H5('Registration Page'),
        html.Br(),
        dcc.Input(id='reg-email', type='email', placeholder='Email'),
        dcc.Input(id='reg-password', type='password', placeholder='Password'),
        html.Button('Register', id='register-button', className='btn btn-sm'),
        html.Div(id='registration-output')
    ])

def layout_admin():
    """
    Admin page layout with text fields for admin email/password
    and buttons to add/update/delete users.
    """
    return html.Div([
        html.Br(),
        html.Br(),
        html.H5('Admin Page'),
        html.Br(),
        dcc.Input(id='admin-email', type='email', placeholder='Email'),
        dcc.Input(id='admin-password', type='password', placeholder='Password'),
        html.Button('Add User', id='admin-add-button'),
        html.Button('Update User', id='admin-update-button'),
        html.Button('Delete User', id='admin-delete-button'),
        html.Div(id='admin-output')
    ])

def layout_main(txt, ocr_txt, user=None):
    """
    Main layout of the entire application. It includes:
      - A login section (user_login)
      - Quickstart sample sections
      - A 'dummy' div for problem loading spinner
      - A 'problem-display' div that is never wrapped in dcc.Loading
        so that Submit events do NOT trigger the spinner
      - Suneung sets and exercise sections, including a dropdown for Problem
      - Additional sections like writing tutor, if needed
    Every docstring and comment is in English, to comply with user instructions.
    """

    app_title = 'LevelUp English 2024'

    # 1) Login Section
    login_section = user_login(user)

    # QUICKSTART Section
    quickstart_header = html.Div('QUICKSTART', id='quickstart-section', className='card-header')
    quickstart_subtitle = html.H6(
        'Listening and Reading Comprehension',
        className='card-subtitle text-muted'
    )

    quickstart_sample = html.Div([
        html.Div(id='top'),
        html.P(),
        dcc.Loading(
            id='loading-textarea',
            children=[
                dcc.Textarea(
                    value=txt,
                    id='textarea',
                    rows='12',
                    className='form-control mx-0',
                    style={
                        'font-family': '"Noto Serif KR", serif',
                        'background-color': '#EBECE8',
                        'color': '#252525',
                    },
                ),
            ],
            type='graph',
            className='loading-indicator',
        ),
        dcc.Store(id='textarea-store'),
        html.P(id='textarea-loading')
    ])
    quickstart_buttons0 = html.Div([
        html.Div([
            html.Button('US SPEAK', id='quickstart-speak', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-dark'),
            html.Button('GB SPEAK', id='quickstart-speak-gb', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-dark'),
            html.Button('QUIZ', id='quickstart-quiz', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-dark'),
        ], style={'display': 'block', 'text-align': 'center', 'margin': '0 auto'}),
    ], className='my-1', style={'width': '100%'})

    quickstart_buttons1 = html.Div([
        html.Div([
            html.Button('GOOGLE E한', id='quickstart-trans', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-dark'),
            html.Button('GPT E한', id='quickstart-trans-gpt', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-dark'),
            html.Button('STUDY', id='quickstart-study', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-dark'),
            html.Button('ILLUSTRATE', id='quickstart-draw', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-dark'),
        ], style={'display': 'block', 'text-align': 'center', 'margin': '0 auto'}),
    ], className='my-1', style={'width': '100%'})

    quickstart_buttons2 = html.Div([
        html.Div([
            html.Button('CORRECT', id='quickstart-correct', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-secondary'),
            html.Button('SIMPLIFY', id='quickstart-simplify', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-secondary'),
            html.Button('ELEVATE', id='quickstart-elevate', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-secondary'),
        ], style={'display': 'block', 'text-align': 'center', 'margin': '0 auto'}),
    ], className='my-1', style={'width': '100%'})

    quickstart_buttons3 = html.Div([
        html.Div([
            html.Button('DESCRIBE', id='quickstart-describe', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-secondary'),
            html.Button('ARGUE', id='quickstart-argue', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-secondary'),
            html.Button('NARRATE', id='quickstart-narrate', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-secondary'),
        ], style={'display': 'block', 'text-align': 'center', 'margin': '0 auto'}),
    ], className='my-1', style={'width': '100%'})

    quickstart_buttons4 = html.Div([
        html.Div([
            html.Button('RECONTEXT', id='quickstart-recontext', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-secondary'),
            html.Button('IMAGINE', id='quickstart-reimagine', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-secondary'),
            html.Button('INVENT', id='quickstart-reinvent', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-secondary'),
        ], style={'display': 'block', 'text-align': 'center', 'margin': '0 auto'}),
        dbc.Button(
            'Scroll to Exercise', 
            id='scroll-to-exercise-button', 
            className='mt-1', 
            color='secondary', 
            outline=True
        ), 
    ], className='my-1', style={'width': '100%'})

    draw_section = html.Div(id='draw')
    draw_loading = dcc.Loading(id='loading-draw', children=[draw_section], type='graph', className='loading-indicator')
      
    trans_section = html.Div(id='translate')
    trans_loading = dcc.Loading(id='loading-trans', children=[trans_section], type='graph', className='loading-indicator')

    trans_gpt_section = html.Div(id='translate-gpt')
    trans_gpt_loading = dcc.Loading(id='loading-trans', children=[trans_gpt_section], type='graph', className='loading-indicator')

    quiz_section = html.Div(id='quiz')
    quiz_loading = dcc.Loading(id='loading-quiz', children=[quiz_section], type='graph', className='loading-indicator')

    study_section = html.Div(id='study')
    study_loading = dcc.Loading(id='loading-study', children=[study_section], type='graph', className='loading-indicator')

    quickstart_body = html.Div([
        quickstart_subtitle,
        quickstart_sample,
        quickstart_buttons0,
        html.Div(id='speak'),
        quiz_loading,
        trans_loading,
        trans_gpt_loading,
        study_loading,
        draw_loading,
        html.Hr(),
        quickstart_buttons1,
        quickstart_buttons2,
        html.Hr(),
        quickstart_buttons3,
        quickstart_buttons4,
    ], className='card-body mt-1')
    quickstart_footer = html.Div(
        className='card-footer text-muted',
        children=html.Div('Step Closer to Your Academic Goals.'),
    )

    # WRITING TUTOR Section (if needed)
    tutor_header = html.Div('WRITING TUTOR', id='tutor-section', className='card-header')

    pdf_subtitle = html.H6('Optical Character Recognition', className='card-subtitle text-muted')

    try:
        with open('app/assets/camera.svg', 'r', encoding='utf-8') as f:
            camera_svg = f.read()
        b64_camera_svg = base64.b64encode(camera_svg.encode()).decode()
        svg_camera = html.Div(
            html.Img(
                id='open-camera-modal-button',
                src=f'data:image/svg+xml;base64,{b64_camera_svg}',
                style={
                    'cursor': 'pointer',
                    'width': '70px', 'height': '70px',
                    'display': 'block'
                },
                n_clicks=0
            ), className='my-0',
        )
    except:
        svg_camera = html.Button(
            'Cam',
            id='open-camera-modal-button',
            n_clicks=0,
            style={'width':'70px','height':'70px'}
        )

    camera_modal = dbc.Modal(
        [
            dbc.ModalHeader("Camera Live Preview", id="camera-modal-header"),
            dbc.ModalBody([
                # <video> for live streaming
                html.Video(
                    id="modal-camera-video",
                    autoPlay=True,
                    style={"width":"100%","height":"auto","backgroundColor":"#333"}
                )
            ]),
            dbc.ModalFooter([
                dbc.Button("OK", id="camera-modal-ok", n_clicks=0, className="mx-1 btn btn-sm btn-outline-primary"),
                dbc.Button("Cancel", id="camera-modal-cancel", n_clicks=0, className="mx-1 btn btn-sm btn-outline-secondary")
            ])
        ],
        id="camera-modal",
        is_open=False,
        centered=True,
        backdrop='static',
        keyboard=False
    )

    pdf_upload = html.Div([
        dbc.Row([
            dbc.Col(
                html.Div('Capture text using your camera or drag and drop an image file containing text.', className='text-muted'),
            )
        ], className='mt-1 mb-3'),
        dbc.Row([
            dbc.Col([
                html.Div([
                    html.Div(
                        svg_camera,
                        style={
                            'width': '70px',
                            'height': '70px',
                            'position': 'absolute',
                            'left': '0'
                        }
                    ),
                    dcc.Upload(
                        html.Div('UPLOAD AN IMAGE FILE HERE'),
                        id='upload-data',
                        style={
                            'cursor': 'pointer',
                            'backgroundColor': '#EBECE825',
                            'color': '#1A1A1A',
                            'height': '70px',
                            'lineHeight': '70px',
                            'borderWidth': '1px',
                            'borderStyle': 'dashed',
                            'borderRadius': '10px',
                            'textAlign': 'center',
                            'position': 'absolute',
                            'left': 'calc(70px + 1rem)',
                            'right': '0'
                        },
                        multiple=False
                    )
                ], style={
                    'position': 'relative',
                    'height': '70px'
                })
            ])
        ])
    ])

    pdf_sample = html.Div([
        html.P(),
        dcc.Loading(
            id='loading-ocr-textarea',
            children=[
                dcc.Textarea(
                    value=ocr_txt,
                    id='ocr-textarea',
                    placeholder='',
                    rows='12',
                    className='form-control mx-0 serif',
                    style={
                        'background-color': '#EBECE8',
                        'color': '#252525',
                    },
                ),
            ],
            type='graph',
            className='loading-indicator',
        ),
        dcc.Store(id='ocr-textarea-store'),
        html.P(id='ocr-textarea-loading'),
        # Optional: preview from camera
        html.Div(id='camera-output', style={'display':'none'})
    ])

    tutor_subtitle = html.H6('Mentored Learning Pathways', className='card-subtitle text-muted')
    us_tutor_section = html.Div(id='american-tutoring', style={'text-align': 'left'})
    kr_tutor_section = html.Div(id='korean-tutoring', style={'text-align': 'left'})
    us_tutor_loading = dcc.Loading(id='loading-us-tutor', children=[us_tutor_section], type='graph')
    kr_tutor_loading = dcc.Loading(id='loading-kr-tutor', children=[kr_tutor_section], type='graph')

    tutor_sample = html.Div([
        html.Div([
            html.H6('TUTOR NATIONALITY', className='my-2 mb-2 card-subtitle text-muted'),
            html.Button('American Tutor', id='us-tutor', n_clicks=0, className='mx-1 mb-1 btn btn-outline-dark'),
            html.Button('Korean Tutor', id='korean-tutor', n_clicks=0, className='mx-1 mb-1 btn btn-outline-dark'),
            us_tutor_loading,
            kr_tutor_loading,
            html.P('', className='my-1'),
        ], style={'display': 'block', 'text-align': 'center', 'margin': '0 auto'}),
    ], className='my-1', style={'width': '100%'})

    tutor_body = html.Div([
        html.Div(id='tutor'),
        pdf_subtitle,
        pdf_upload,
        pdf_sample,
        html.Hr(),
        tutor_subtitle,
        tutor_sample,
    ], className='card-body my-1')

    tutor_footer = html.Div(
        className='card-footer text-muted pb-1',
        children=html.Div('Personalized guidance accelerates learning.'),
    )

    # SUNEUNG Section (if needed)
    suneung_header = html.Div('수능 SET', id='suneung-set-section', className='card-header')
    suneung_subtitle = html.H6('Personal Study Archive', className='card-subtitle text-muted')
    suneung_sample = html.Div([
        html.P('', className='my-1'),
        html.Div(id='login-output'),
        html.P(),
    ])

    suneung_buttons = html.Div([
        html.Div([
            html.H6('수능 SET CREATION', className='my-2 mb-2 card-subtitle text-muted'),
            html.Button(
                'Create New Set',
                id='suneung1',
                n_clicks=0,
                className='mx-1 mb-1 btn btn-secondary',
                title='Create a new set'
            ),
            html.Button(
                'By Type',
                id='suneung2',
                n_clicks=0,
                className='mx-1 mb-1 btn btn-secondary',
                disabled=True,
                style={'display': 'none'}
            ),
            html.Button(
                'Previous Archive',
                id='suneung3',
                n_clicks=0,
                className='mx-1 mb-1 btn btn-danger',
                title='View previously created sets in the archive'
            ),
            html.Hr(),
            html.P('', className='my-1'),
            html.Div(id='file-list', style={'text-align': 'left'}),
            html.Div(id='file-content')
        ], style={'display': 'block', 'text-align': 'center', 'margin': '0 auto'}),
    ], className='my-1', style={'width': '100%'})

    suneung_set_section = html.Div(id='suneung-set')
    suneung_set_loading = dcc.Loading(
        id='loading-suneung-set',
        children=[suneung_set_section],
        type='graph',
        className='loading-indicator',
    )

    suneung_body = html.Div([
        suneung_subtitle,
        suneung_sample,
        html.Div(id='recent-files'),
        html.Hr(),
        suneung_buttons,
        suneung_set_loading,
    ], className='card-body my-1')

    suneung_footer = html.Div(
        className='card-footer text-muted pb-1',
        children=html.Div('Step Closer to Your Academic Goals.'),
    )

    # EXERCISE Section with dummy-based spinner approach
    exercise_header = html.Div('EXERCISE', id='exercise-section', className='card-header')
    exercise_subtitle = html.H6('Simulated Exam Experience', className='card-subtitle text-muted')

    # 1) Create a hidden dummy div for spinner triggers
    loading_dummy_div = html.Div(
        id='loading-dummy',
        children='',
        style={'display': 'none'}
    )

    # 2) Wrap that dummy div with dcc.Loading
    loading_dummy_wrapper = dcc.Loading(
        id='problem-loading',
        children=loading_dummy_div,
        type='graph'
    )

    # 3) The problem display area, separate from the spinner
    problem_display_div = html.Div(
        'Problems equivalent to those found in 수능, 내신, and global examinations are presented here. '
        'You can solve these problems and view their explanations. Select a problem from the dropdown menu.',
        id='problem-display',
        className='form-control mx-0 mb-3 py-1 serif',
        style={
            'min-height': '100px',
            'white-space': 'pre-wrap',
            'color': '#101010',
            'background-color': '#EBECE890',
            'margin-top': '10px'
        }
    )

    # skip_ls => disable in the dropdown
    skip_ls = ['41_42','43_45']
    problem_items = [
        dbc.DropdownMenuItem(
            f"Problem {i_str}",
            id={"type": "problem-item", "index": f"{i_str}"},
            disabled=(i_str in skip_ls),
            className='my-0 py-0',
            style={'font-size': '0.8rem'}
        ) for i_str in [str(i) for i in range(18,41)] + skip_ls
    ]

    exercise_sample = html.Div([
        html.Div([
            html.H6('EXAM TYPES', className='my-2 mb-2 card-subtitle text-muted'),
            html.Button('수능', id='exercise-suneung', n_clicks=0, className='mx-1 mb-1 btn btn-info'),
            html.Button('내신', id='exercise-grade', n_clicks=0, className='mx-1 mb-1 btn btn-success'),
            html.Button('International', id='exercise-international', n_clicks=0, className='mx-1 mb-1 btn btn-warning'),
        ], style={'display': 'block', 'text-align': 'center', 'margin': '0 auto'}),

        html.Div(
            id='suneung-container',
            style={'display': 'none','margin-top':'10px'},
            children=[
                dbc.DropdownMenu(
                    label="Problem",
                    children=problem_items,
                    toggle_style={'width': '10rem', 'background-color': '#299dcb'},
                    toggle_class_name='btn btn-sm btn-outline-dark',
                    nav=False,
                    in_navbar=False
                ),
                # The dummy approach
                loading_dummy_wrapper,  # triggers spinner only on updates to 'loading-dummy'
                problem_display_div     # actual problem content, not wrapped => no spinner on submit
            ]
        ),
        html.Hr()
    ], className='my-1', style={'width': '100%'})

    exercise_buttons = html.Div([
        html.Div([
            html.H6('HIGHLEVEL DRILLS', className='my-2 mb-1 card-subtitle text-muted'),
            html.P(),
            html.Button('BLANK', id='exercise-blank', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-dark'),
            html.Button('ORDERING', id='exercise-ordering', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-dark'),
            html.Button('INSERTION', id='exercise-insertion', n_clicks=0, className='mx-1 mb-1 btn btn-sm btn-outline-dark'),
        ], style={'display': 'block', 'text-align': 'center', 'margin': '0 auto'}),
    ], className='my-1', style={'width': '100%'})

    exercise_body = html.Div([
        html.Div(id='exercise'),
        exercise_subtitle,
        exercise_sample,
        exercise_buttons
    ], className='card-body my-1')

    exercise_footer = html.Div(
        className='card-footer text-muted pb-1',
        children=html.Div('Solving problems is the shortcut to understanding.'),
    )

    # Potentially embed custom SVG images, if the user has them
    try:
        with open('app/assets/tutor.svg', 'r', encoding='utf-8') as f:
            tutor_svg = f.read()
        b64_tutor_svg = base64.b64encode(tutor_svg.encode()).decode()
        svg_tutor = html.Div(
            html.Img(
                src=f'data:image/svg+xml;base64,{b64_tutor_svg}',
                style={'width': '60%', 'display': 'block'},
            ), className='my-0',
        )
    except:
        svg_tutor = html.Div()

    try:
        with open('app/assets/students.svg', 'r', encoding='utf-8') as f:
            students_svg = f.read()
        b64_students_svg = base64.b64encode(students_svg.encode()).decode()
        svg_students = html.Div(
            html.Img(
                src=f'data:image/svg+xml;base64,{b64_students_svg}',
                style={'width': '60%', 'display': 'block', 'margin': '0 auto'},
            ), className='mt-0 mb-3',
        )
    except:
        svg_students = html.Div()

    layout_main_div = html.Div([
        html.H4(app_title, className='mt-3'),
        html.Div(id='js', style={'display': 'none'}),

        # Login section
        login_section,

        # QUICKSTART
        html.Div([
            quickstart_header,
            quickstart_body,
            quickstart_footer,
        ], className='card mb-3 py-1'),

        # Suneung
        html.Div([
            suneung_header,
            suneung_body,
            suneung_footer,
        ], className='card mb-3 py-1'),

        # EXERCISE
        html.Div([
            exercise_header,
            exercise_body,
            exercise_footer,
        ], className='card mb-2 py-1'),

        svg_tutor,

        # WRITING TUTOR
        html.Div([
            tutor_header,
            tutor_body,
            tutor_footer,
        ], className='card mb-3 py-1'),

        dbc.Button(
            'Scroll to the top',
            id='scroll-button',
            className='mt-1 mb-4',
            color='secondary',
            outline=True
        ),
        svg_students,
        html.P('', className='my-3 mt-1'),
    ])

    return layout_main_div