import React, { useState } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { Radio } from 'antd';
import { ArrowLeft } from 'lucide-react';
import { Button } from '../ui/button';
import SlotsList from './SlotsList';
import MapData from './MapData';

export default function LockCabinetDetail() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const cabinetId = searchParams.get('cabinetId') || '';
  const [tabPosition, setTabPosition] = useState<'first' | 'second'>('first');

  const currentComponent = tabPosition === 'first' ? <MapData cabinetId={cabinetId} /> : <SlotsList cabinetId={cabinetId} />;

  const handleBack = () => {
    // 读取来源菜单信息，如果存在则使用它，否则默认使用硬件管理 -> 机柜
    let menuInfo = { menu: 'hardwareManagement', subMenu: 'cabinet' }; // 默认值
    
    try {
      const sourceMenuStr = sessionStorage.getItem('cabinetDetailSource');
      if (sourceMenuStr) {
        const sourceMenu = JSON.parse(sourceMenuStr);
        menuInfo = { menu: sourceMenu.menu, subMenu: sourceMenu.subMenu };
        // 清除来源菜单信息（已使用）
        sessionStorage.removeItem('cabinetDetailSource');
      }
    } catch (e) {
      console.error('解析来源菜单信息失败:', e);
    }
    
    // 通过 sessionStorage 告诉 Dashboard 恢复菜单状态（它在挂载时会读取 navigateToMenu）
    sessionStorage.setItem('navigateToMenu', JSON.stringify(menuInfo));
    sessionStorage.setItem('lastActiveMenu', JSON.stringify(menuInfo));

    // 回到 Dashboard（应用主要以 Dashboard 内部状态渲染各菜单内容）
    navigate('/dashboard');
  };

  return (
    <div className="p-4">
      <div className="mb-4 flex items-center justify-between">
        <Button
          variant="ghost"
          onClick={handleBack}
          className="flex items-center gap-2"
        >
          <ArrowLeft className="w-4 h-4" />
          返回机柜列表
        </Button>
        <Radio.Group value={tabPosition} onChange={(e) => setTabPosition(e.target.value)}>
          <Radio.Button value="first">锁柜视图</Radio.Button>
          <Radio.Button value="second">列表视图</Radio.Button>
        </Radio.Group>
      </div>
      {currentComponent}
    </div>
  );
}

