import React, { useState, useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { Modal, Input, message, Button } from 'antd';
import { CopyOutlined, DownloadOutlined, UploadOutlined, ReloadOutlined, LeftOutlined } from '@ant-design/icons';
import MapData from './MapData';
import { lockCabinetApi, LockCabinetVO } from '../../api/lockCabinet';

export default function LockCabinetDetail() {
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
  const cabinetId = searchParams.get('cabinetId') || '';
  const [refreshKey, setRefreshKey] = useState(0);
  const [cabinetInfo, setCabinetInfo] = useState<LockCabinetVO | null>(null);

  // 钥匙/锁状态 JSON：存储在机柜 remark 字段，用于导出/导入弹框
  const [exportVisible, setExportVisible] = useState(false);
  const [exportContent, setExportContent] = useState('');
  const [importVisible, setImportVisible] = useState(false);
  const [importJson, setImportJson] = useState('');

  useEffect(() => {
    if (cabinetId) {
      lockCabinetApi.selectIsLockCabinetById(Number(cabinetId))
        .then(setCabinetInfo)
        .catch((err: any) => {
          console.error('获取机柜信息失败:', err);
          message.error(err?.message || '获取机柜信息失败');
        });
    } else {
      setCabinetInfo(null);
    }
  }, [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');
  };

  const handleRefresh = () => {
    // 通过改变 key 来强制刷新 MapData 组件
    setRefreshKey(prev => prev + 1);
  };

  // 导出 JSON：将 remark 内容展示在弹框中（多行文本）
  const handleExportJson = () => {
    const raw = cabinetInfo?.remark ?? '';
    try {
      const parsed = raw.trim() ? JSON.parse(raw) : null;
      setExportContent(parsed !== null ? JSON.stringify(parsed, null, 2) : '');
    } catch {
      setExportContent(raw);
    }
    setExportVisible(true);
  };

  // 复制 JSON 到剪贴板
  const handleCopyJson = async () => {
    if (!exportContent.trim()) {
      message.warning('没有可复制的内容');
      return;
    }
    try {
      await navigator.clipboard.writeText(exportContent);
      message.success('复制成功，JSON 已复制到剪贴板');
    } catch (err: any) {
      message.error(err?.message || '复制失败');
    }
  };

  // 导入 JSON：将弹框中的内容写入 remark 并调用机柜编辑接口（后端需要 id 作为主键）
  const handleImportJson = async () => {
    const trimmed = importJson.trim();
    try {
      if (trimmed) {
        JSON.parse(trimmed);
      }
    } catch {
      message.error('JSON 格式错误，请检查后重试');
      return;
    }
    const primaryId = (cabinetInfo as any)?.id ?? cabinetInfo?.cabinetId;
    if (!primaryId) {
      message.error('机柜信息不存在，无法保存');
      return;
    }
    try {
      const payload: LockCabinetVO & { id?: number } = {
        ...cabinetInfo,
        cabinetName: cabinetInfo!.cabinetName,
        remark: trimmed,
      };
      (payload as any).id = primaryId;
      delete (payload as any).cabinetId;
      await lockCabinetApi.updateIsLockCabinet(payload as LockCabinetVO);
      setCabinetInfo(prev => prev ? { ...prev, remark: trimmed } : null);
      setRefreshKey(prev => prev + 1);
      setImportVisible(false);
      setImportJson('');
      message.success('导入成功，钥匙/锁状态已更新');
    } catch (err: any) {
      message.error(err?.message || '保存失败');
    }
  };

  const openImportModal = () => {
    const raw = cabinetInfo?.remark ?? '';
    try {
      const parsed = raw.trim() ? JSON.parse(raw) : null;
      setImportJson(parsed !== null ? JSON.stringify(parsed, null, 2) : '');
    } catch {
      setImportJson(raw);
    }
    setImportVisible(true);
  };

  return (
    <div className="h-screen flex flex-col overflow-hidden bg-gradient-to-br from-gray-50 via-blue-50/30 to-gray-50">
      {/* 顶部导航栏 */}
      <nav className="bg-white/80 backdrop-blur-xl border-b border-gray-200/50 shadow-sm sticky top-0 z-50">
        <div className="px-6 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：标题文字 */}
            <div className="flex items-center">
              <h1 className="text-lg text-gray-900 font-semibold">锁控柜可视化管理</h1>
            </div>

            {/* 右侧：导入JSON、导出JSON、刷新和返回按钮（antd 风格） */}
            <div className="flex items-center gap-2">
              <Button type="default" icon={<DownloadOutlined />} onClick={handleExportJson}>
                导出JSON
              </Button>
              <Button type="default" icon={<UploadOutlined />} onClick={openImportModal}>
                导入JSON
              </Button>
              <Button type="primary" icon={<ReloadOutlined />} onClick={handleRefresh}>
                刷新
              </Button>
              <Button type="default" icon={<LeftOutlined />} onClick={handleBack}>
                返回
              </Button>
            </div>
          </div>
        </div>
      </nav>

      {/* 主内容区域 */}
      <div className="flex-1 min-h-0 overflow-hidden p-4">
        <div className="h-full min-h-0">
          <MapData key={refreshKey} cabinetId={cabinetId} />
        </div>
      </div>

      {/* 导出 JSON 弹框：多行文本展示 remark 内容 */}
      <Modal
        open={exportVisible}
        title="钥匙/锁状态 JSON 导出"
        onCancel={() => setExportVisible(false)}
        onOk={() => setExportVisible(false)}
        width={800}
        okText="关闭"
        cancelButtonProps={{ style: { display: 'none' } }}
        style={{ top: 20 }}
        styles={{ body: { maxHeight: 'calc(90vh - 120px)', overflowY: 'auto', overflowX: 'hidden', padding: 0 } }}
      >
        <div className="relative">
          <div className="sticky top-0 bg-white z-10 px-6 py-3 flex justify-end border-b border-gray-100">
            <Button type="default" icon={<CopyOutlined />} onClick={handleCopyJson}>
              复制JSON
            </Button>
          </div>
          <div className="p-6">
            <div className="bg-gray-50 border border-gray-200 rounded-lg p-3 overflow-x-hidden">
              <pre className="text-xs text-gray-800 whitespace-pre-wrap break-words font-mono overflow-x-hidden min-h-[200px]">
                {exportContent || '（暂无数据，请先导入 JSON）'}
              </pre>
            </div>
          </div>
        </div>
      </Modal>

      {/* 导入 JSON 弹框：多行文本编辑，保存到 remark 并调用更新接口 */}
      <Modal
        open={importVisible}
        title="导入钥匙/锁状态 JSON"
        onCancel={() => {
          setImportVisible(false);
          setImportJson('');
        }}
        onOk={handleImportJson}
        width={800}
        okText="导入"
        cancelText="取消"
      >
        <div className="space-y-3">
          <p className="text-sm text-gray-600">
            请粘贴或编辑钥匙仓/锁仓状态 JSON 数据，导入后将更新机柜备注（remark）并刷新页面展示
          </p>
          <Input.TextArea
            value={importJson}
            onChange={(e) => setImportJson(e.target.value)}
            placeholder="请粘贴或输入 JSON 数据..."
            rows={15}
            className="font-mono text-xs"
          />
        </div>
      </Modal>
    </div>
  );
}
