/**
 * H5 设备详情（柜子视图）
 * - 柜子基本信息
 * - 仓板列表，每板6个通道
 * - 点击通道进入通道详情
 */
import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { h5Api, type CabinetDetail } from '../api';
import { ChannelCard, Loading, ErrorState, PageContainer } from '../components';

export default function H5DeviceDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [data, setData] = useState<CabinetDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const fetchDetail = async () => {
    if (!id) return;
    setLoading(true);
    setError('');
    try {
      const res = await h5Api.getCabinetDetail(Number(id));
      setData(res.data);
    } catch {
      setError('加载设备详情失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchDetail();
    // ponytail: no periodic refresh, add if real-time needed
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  if (loading) return <PageContainer title="设备详情"><Loading /></PageContainer>;
  if (error) return <PageContainer title="设备详情"><ErrorState message={error} onRetry={fetchDetail} /></PageContainer>;
  if (!data) return null;

  return (
    <PageContainer title={data.name || data.abstract_id} onBack={() => navigate('/pms/devices')}>
      {/* 设备基本信息 */}
      <div className="mb-4 rounded-xl bg-white p-4">
        <div className="flex items-center justify-between">
          <div>
            <p className="text-base font-semibold text-gray-900">{data.name || data.abstract_id}</p>
            <p className="mt-0.5 text-xs text-gray-500">ID: {data.abstract_id}</p>
            {data.imei && <p className="text-xs text-gray-400">IMEI: {data.imei}</p>}
          </div>
          <span className={`rounded-full px-3 py-1 text-xs font-medium ${data.status === 1 ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>
            {data.status === 1 ? '在线' : '离线'}
          </span>
        </div>
      </div>

      {/* 仓板列表 */}
      {data.cabin_boards.map((board) => (
        <section key={board.id} className="mb-4">
          <h3 className="mb-2 text-sm font-medium text-gray-700">
            仓板 {board.board_id}
            <span className={`ml-2 text-xs ${board.status === 1 ? 'text-green-600' : 'text-gray-400'}`}>
              ({board.status === 1 ? '在线' : '离线'})
            </span>
          </h3>
          <div className="grid grid-cols-3 gap-2">
            {board.compartments.map((comp) => (
              <ChannelCard
                key={comp.id}
                channelId={comp.channel_id}
                status={comp.status}
                voltage={comp.voltage}
                current={comp.current}
                onClick={() => navigate(`/pms/compartments/${comp.id}`)}
              />
            ))}
          </div>
        </section>
      ))}
    </PageContainer>
  );
}
