/**
 * H5 用户端根组件
 */
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { useH5AuthStore } from './auth';
import H5Layout from './layout';
import H5Login from './pages/login';
import H5Home from './pages/home';
import H5Devices from './pages/devices';
import H5DeviceDetail from './pages/device-detail';
import H5CompartmentDetail from './pages/compartment-detail';
import H5Me from './pages/me';
import { Loading } from './components';
import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { h5Api } from './api';

/** 扫码入口处理 */
function ScanRedirect() {
  const { abstractId } = useParams<{ abstractId: string }>();
  const navigate = useNavigate();
  const [error, setError] = useState('');

  useEffect(() => {
    if (!abstractId || ['login', 'devices', 'me', 'compartments'].includes(abstractId)) {
      return;
    }
    h5Api.getCabinetByAbstractId(abstractId)
      .then((res) => navigate(`/devices/${res.data.id}`, { replace: true }))
      .catch(() => setError('未找到该设备'));
  }, [abstractId, navigate]);

  if (error) {
    return (
      <div className="flex min-h-screen flex-col items-center justify-center gap-3 bg-white">
        <p className="text-sm text-gray-500">{error}</p>
      </div>
    );
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-white">
      <Loading />
    </div>
  );
}

export default function App() {
  const restore = useH5AuthStore((s) => s.restore);

  useEffect(() => {
    restore();
  }, [restore]);

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/login" element={<H5Login />} />
        <Route element={<H5Layout />}>
          <Route index element={<H5Home />} />
          <Route path="devices" element={<H5Devices />} />
          <Route path="devices/:id" element={<H5DeviceDetail />} />
          <Route path="me" element={<H5Me />} />
        </Route>
        <Route path="compartments/:id" element={<H5CompartmentDetail />} />
        <Route path=":abstractId" element={<ScanRedirect />} />
        <Route path="*" element={<Navigate to="/" replace />} />
      </Routes>
    </BrowserRouter>
  );
}
