import React, { useContext, useEffect, useState } from 'react';
import { Dropdown } from 'react-bootstrap';
import { fetchData } from '../../fetching/Fetch.js';
import 'bootstrap/dist/css/bootstrap.min.css';
import { SERVER_URL } from '../../constants.js';
import { useNavigate } from 'react-router-dom';
import { UserContext } from '../../context/UserContext.jsx';
import { saveActiveStation } from '../../utils/activeStation.js';

const StationIntroPage = () => {
    const navigate = useNavigate();
    const { user } = useContext(UserContext);

    const [branches, setBranches] = useState([]);
    const [selectedBranch, setSelectedBranch] = useState(null);
    const [stations, setStations] = useState([]);
    const [selectedStation, setSelectedStation] = useState(null);
    const [error, setError] = useState('');
    const [loadingBranches, setLoadingBranches] = useState(false);
    const [loadingStations, setLoadingStations] = useState(false);

    const tenantCode = user?.tenantCode;
    const url = `${SERVER_URL}/api/v1/`;

    useEffect(() => {
        if (!tenantCode) {
            setBranches([]);
            setError('Missing tenant on your account.');
            return;
        }

        setLoadingBranches(true);
        setError('');
        fetchData(`${url}branches/${encodeURIComponent(tenantCode)}`, 'GET')
            .then(({ data, success }) => {
                if (!success) {
                    setBranches([]);
                    setError('Could not load branches for your tenant.');
                    return;
                }
                setBranches(Array.isArray(data) ? data : []);
                if (!data?.length) {
                    setError(`No branches found for tenant ${tenantCode}.`);
                }
            })
            .catch((err) => {
                console.error(err);
                setError('Could not load branches.');
            })
            .finally(() => setLoadingBranches(false));
    }, [tenantCode]);

    function handleBranchSelect(branch) {
        setSelectedBranch(branch);
        setSelectedStation(null);
        setStations([]);
        setLoadingStations(true);
        setError('');

        fetchData(`${url}stations/${encodeURIComponent(tenantCode)}/${branch.id}`, 'GET')
            .then(({ data, success }) => {
                if (!success) {
                    setStations([]);
                    setError('Could not load stations for this branch.');
                    return;
                }
                setStations(Array.isArray(data) ? data : []);
                if (!data?.length) {
                    setError('No stations found for this branch.');
                }
            })
            .catch((err) => {
                console.error(err);
                setError('Could not load stations.');
            })
            .finally(() => setLoadingStations(false));
    }

    function handleStationSelect(station) {
        setSelectedStation(station);
        saveActiveStation({
            stationId: station.id,
            stationName: station.name,
            branchId: selectedBranch?.id,
            branchName: selectedBranch?.name,
        });
        navigate(`/teller-queue/${station.id}`, {
            state: {
                station,
                branch: selectedBranch,
            },
        });
    }

    return (
        <div className="text-center mt-5">
            <div className="border p-3" style={{ maxWidth: '500px', margin: '0 auto' }}>
                <h1 className="mb-2">Pilih Cawangan dan Kaunter</h1>
                {tenantCode ? (
                    <p className="text-muted mb-4">Syarikat: {tenantCode}</p>
                ) : null}

                {error ? <p className="text-danger">{error}</p> : null}

                <Dropdown>
                    <Dropdown.Toggle
                        variant="primary"
                        id="dropdown-branch"
                        style={{ width: '100%' }}
                        disabled={loadingBranches || branches.length === 0}
                    >
                        {loadingBranches
                            ? 'Loading cawangan…'
                            : selectedBranch
                                ? selectedBranch.name
                                : 'Pilih Cawangan'}
                    </Dropdown.Toggle>
                    <Dropdown.Menu style={{ width: '100%' }}>
                        {branches.map((branch) => (
                            <Dropdown.Item
                                key={branch.id}
                                onClick={() => handleBranchSelect(branch)}
                            >
                                {branch.name}
                            </Dropdown.Item>
                        ))}
                    </Dropdown.Menu>
                </Dropdown>

                {selectedBranch ? (
                    <div className="mt-3">
                        <Dropdown>
                            <Dropdown.Toggle
                                variant="primary"
                                id="dropdown-station"
                                style={{ width: '100%' }}
                                disabled={loadingStations || stations.length === 0}
                            >
                                {loadingStations
                                    ? 'Loading kaunter…'
                                    : selectedStation
                                        ? selectedStation.name
                                        : 'Pilih Kaunter'}
                            </Dropdown.Toggle>
                            <Dropdown.Menu style={{ width: '100%' }}>
                                {stations.map((station) => (
                                    <Dropdown.Item
                                        key={station.id}
                                        onClick={() => handleStationSelect(station)}
                                    >
                                        {station.name}
                                    </Dropdown.Item>
                                ))}
                            </Dropdown.Menu>
                        </Dropdown>
                    </div>
                ) : null}
            </div>
        </div>
    );
};

export default StationIntroPage;
