import React, { useState, useEffect, useContext } from 'react';
import { Layout, Select, Spin, Space, Breadcrumb, Switch, Avatar, Menu, Dropdown, Modal, Typography } from 'antd';
import { authenticationService } from '../../_services';
import { selectorService } from '../../services/selectorService';
import { useTranslation } from 'react-i18next';
import { uniqueId } from 'lodash';
import { Link, useHistory } from 'react-router-dom';
import { CaretDownFilled, CaretRightOutlined, UserOutlined } from '@ant-design/icons';
import axios from 'axios'; // 👈 Make sure axios is imported

import { RepeatedData } from '../RepeatedDataProvider';
import { ReactComponent as LocaleSVG } from '../assets/image/locale-icon.svg';
import { ReactComponent as ClassSVG } from '../assets/image/class-icon.svg';
import './Headerc.css';
import { breadcrumbSetter } from './BreadcrumbSetter';
import { useTheme } from '../../Theme/useTheme';
import ExpandCollapse from '../ExpandCollapse';

const { Header } = Layout;

const Headerc = (props) => {
    const { data, setData } = useContext(RepeatedData);
    const { t, i18n } = useTranslation();
    const history = useHistory();
    const [darkMode, setDarkMode] = useTheme();

    const [page, setPage] = useState([]);

    const [state, setState] = useState({
        user: authenticationService.currentUserValue,
        refresh: false,
        language_code: "",
        language_name: "",
        classID: "",
        batch_id: "",
    });

    const [languages, setlanguages] = useState([]);
    const [classes, setClasses] = useState([]);
    const [batches, setBatches] = useState([]);
    const [loadingBatches, setLoadingBatches] = useState(false); // 👈 Loading flag for batches

    const config = {
        title: <Typography.Paragraph strong>Switch to {darkMode ? <span>Light</span> : <span>Dark</span>} mode?</Typography.Paragraph>,
        content: (
            <>
                <Typography.Text type='warning'>Warning!</Typography.Text> Any unsaved work will be lost and the page will reload! <br />
                Do you still want to continue?
            </>
        ),
        maskClosable: true,
        onOk: () => setDarkMode(!darkMode),
        closable: true,
        okText: 'Continue',
    };

    useEffect(() => {
        setPage(breadcrumbSetter(props.location.pathname));
    }, [props.location.pathname]);

    function itemRender(route, params, pages, paths) {
        const last = pages.indexOf(route) === pages.length - 1;
        return last ? (
            <>{route.breadcrumbName}</>
        ) : (
            <Link to={route.path}><>{route.breadcrumbName}</></Link>
        );
    }

    useEffect(() => {
        if (!authenticationService.currentUserValue.language_code) {
            if (!JSON.parse(sessionStorage.getItem('currentUser')).language_code) {
                const storedUser = JSON.parse(sessionStorage.getItem('currentUser'));
                storedUser.language_code = i18n.language;
                authenticationService.currentUserValue.language_code = i18n.language;
                setState(prev => ({ ...prev, language_code: i18n.language }));
                sessionStorage.setItem('currentUser', JSON.stringify(storedUser));
            } else {
                authenticationService.currentUserValue.language_code = JSON.parse(sessionStorage.getItem('currentUser')).language_code;
                setState(prev => ({ ...prev, language_code: JSON.parse(sessionStorage.getItem('currentUser')).language_code }));
            }
        } else {
            i18n.changeLanguage(authenticationService.currentUserValue.language_code);
            setState(prev => ({ ...prev, language_code: authenticationService.currentUserValue.language_code }));
        }
        handleLoad();
        fetchBatches(); // 👈 Load batches
    }, [state.user, state.language_code]);

    /** ✅ Fetch Batches like Languages **/
    const fetchBatches = async () => {
        try {
            setLoadingBatches(true);

            const token = sessionStorage.getItem("currentToken");

            if (!token) {
                console.warn("⚠️ No token found — cannot fetch batches");
                setLoadingBatches(false);
                return;
            }

            const response = await axios.get(
                "https://api.practicekea.com/api-student/v1/UserGroups/list",
                {
                    headers: {
                        Authorization: `Bearer ${token}`,
                    },
                }
            );

            const batchData = response?.data?.result || [];
            setBatches(batchData);

            // Persist last selected batch if available
            const storedUser = JSON.parse(sessionStorage.getItem("currentUser")) || {};
            if (storedUser.batch_id) {
                setState(prev => ({ ...prev, batch_id: storedUser.batch_id }));
            } else if (batchData.length > 0) {
                // Default to first batch
                storedUser.batch_id = batchData[0].id;
                authenticationService.currentUserValue.batch_id = batchData[0].id;
                setState(prev => ({ ...prev, batch_id: batchData[0].id }));
                sessionStorage.setItem("currentUser", JSON.stringify(storedUser));
            }

        } catch (error) {
            console.error("❌ Failed to fetch batches:", error);
        } finally {
            setLoadingBatches(false);
        }
    };

    function handleLoad() {
        selectorService.loadLanguages().then(langData => {
            if (!langData) {
                authenticationService.refreshFireToken().then(() => {
                    setState({
                        user: authenticationService.currentUserValue,
                        refresh: true
                    });
                });
            }
            if (langData) {
                const result = langData.result;
                setlanguages(result);
                props.setLanguage(result);
            }
        });

        if (authenticationService.currentUserValue?.role_id !== 4) {
            const result = data.classes ? data.classes : [];
            setClasses(result);
            const currentClass = authenticationService.currentClassValue;
            if (currentClass) {
                setState((prev) => ({ ...prev, classID: currentClass }));
            }
            if (currentClass === null && result.length > 0) {
                authenticationService.updateClass(result[0].name, result[0].id);
                setState((prev) => ({ ...prev, classID: result[0].id }));
            }
            props.isClassLoading && props.isClassLoading(false);
            setData(prev => ({ ...prev, queue: { ...prev.queue, classIsSet: true } }));
        }
    }

    /** ✅ Handle Batch Change **/
    const onClickBatchChange = (_, objectSelected) => {
        authenticationService.currentUserValue.batch_id = objectSelected.value;
        const storedUser = JSON.parse(sessionStorage.getItem("currentUser")) || {};
        storedUser.batch_id = objectSelected.value;
        sessionStorage.setItem("currentUser", JSON.stringify(storedUser));
        setState(prev => ({ ...prev, batch_id: objectSelected.value }));
    };

    function onClickLanguageChange(_, objectSelected) {
        authenticationService.currentUserValue.language_code = objectSelected.value;
        authenticationService.currentUserValue.language_name = objectSelected.children;
        setState((prev) => ({
            ...prev,
            language_code: objectSelected.value,
            language_name: objectSelected.children
        }));
        sessionStorage.setItem('currentUser', JSON.stringify(authenticationService.currentUserValue));
        i18n.changeLanguage(objectSelected.value);
        history.push(props.location.pathname);
    }

    function onClickClassChange(_, objectSelected) {
        authenticationService.updateClass(objectSelected.children, objectSelected.value);
        window.location.reload();
    };

    function logout() {
        authenticationService.logout();
        history.push('/login');
    }

    function profileMenuDropdown({ key }) {
        if (key === "1") return history.push("/profile-page");
        if (key === "2") return history.push("/legal");
        if (key === "3") return logout();
    }

    const menu = (
        <Menu onClick={profileMenuDropdown}>
            <Menu.Item key="1">Profile</Menu.Item>
            <Menu.Item key="2">Terms & Privacy</Menu.Item>
            <Menu.Item key="3">Logout</Menu.Item>
        </Menu>
    );

    return (
        <Header className="app-header">
            <div className='left'>
                <Breadcrumb key={uniqueId()} separator={<CaretRightOutlined />} itemRender={itemRender} routes={page} />
            </div>
            <div className='right'>
                <ExpandCollapse>
                    <Switch
                        checkedChildren={"Dark"}
                        unCheckedChildren={"Day"}
                        checked={darkMode}
                        onChange={() => Modal.warning(config)}
                    />

                    {/* 🎓 Batch Selector (NEW SECTION) */}
                    <Select
                        size='normal'
                        placeholder={<><ClassSVG /> Loading Batches...</>}
                        optionLabelProp="label"
                        loading={loadingBatches}
                        dropdownRender={(menu) => (
                            <>
                                {loadingBatches ? (
                                    <Space style={{ display: 'flex', justifyContent: 'center', flexDirection: 'column', padding: 10 }}>
                                        <Spin />
                                        Loading batches...
                                    </Space>
                                ) : batches && batches.length > 0 ? menu : (
                                    <Space style={{ display: 'flex', justifyContent: 'center', flexDirection: 'column', padding: 10 }}>
                                        No batches to display
                                    </Space>
                                )}
                            </>
                        )}
                        dropdownClassName="batch-select-dropdown"
                        onChange={onClickBatchChange}
                        value={batches.length > 0 ? state.batch_id : undefined}
                    >
                        {batches.map((batchItem) => (
                            <Select.Option
                                key={batchItem.id}
                                value={batchItem.id}
                                label={<><ClassSVG />&nbsp;{batchItem.name}</>}
                            >
                                {batchItem.name}
                            </Select.Option>
                        ))}
                    </Select>

                    {/* 🌐 Language Selector */}
                    <Select
                        size='normal'
                        placeholder={<><LocaleSVG /> Language Loading...</>}
                        optionLabelProp="label"
                        dropdownRender={(menu) => (
                            <>
                                {languages.length > 0 ? menu : (
                                    <Space style={{ display: 'flex', justifyContent: 'center', flexDirection: 'column', padding: 10 }}>
                                        <Spin />
                                        Loading languages, please wait...
                                    </Space>
                                )}
                            </>
                        )}
                        onChange={onClickLanguageChange}
                        value={languages.length > 0 ? state.language_code : undefined}
                    >
                        {languages.map((languageItem) => (
                            <Select.Option
                                key={languageItem.code}
                                value={languageItem.code}
                                label={<><LocaleSVG />&nbsp;{languageItem.name}</>}
                            >
                                {languageItem.name}
                            </Select.Option>
                        ))}
                    </Select>

                    {/* 🏫 Class Selector */}
                    {authenticationService.currentUserValue?.role_id !== 4 ? (
                        <Select
                            size='normal'
                            placeholder={<><ClassSVG /> Loading Classes...</>}
                            optionLabelProp="label"
                            dropdownRender={(menu) => (
                                <>
                                    {classes && classes.length > 0 ? menu : (
                                        <Space style={{ display: 'flex', justifyContent: 'center', flexDirection: 'column', padding: 10 }}>
                                            <Spin />
                                            No classes to display
                                        </Space>
                                    )}
                                </>
                            )}
                            dropdownClassName="class-select-dropdown"
                            onChange={onClickClassChange}
                            value={classes.length > 0 ? state.classID : undefined}
                        >
                            {classes.map((classItem) => (
                                <Select.Option
                                    key={classItem.id}
                                    value={classItem.id}
                                    label={<><ClassSVG />&nbsp;{classItem.name}</>}
                                >
                                    {classItem.name}
                                </Select.Option>
                            ))}
                        </Select>
                    ) : null}
                </ExpandCollapse>

                <div>
                    <Dropdown overlay={menu} trigger={['hover', 'click']}>
                        <span className='center-flex'>
                            <Avatar style={{ flex: "0 0 32px" }} size={"default"} src={state.user.photo} icon={<UserOutlined />} />
                            <CaretDownFilled size={14} className='ml-3-0' />
                        </span>
                    </Dropdown>
                </div>
            </div>
        </Header>
    );
};

export default Headerc;
