/**
 * H5 设备页
 * - 项目列表 → 选择项目后显示设备列表
 * - 点击设备进入设备详情
 */
import { useEffect, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { h5Api, type H5Project, type H5Cabinet } from '../api';
import { Loading, ErrorState, PageContainer } from '../components';

type ViewMode = 'projects' | 'cabinets';

export default function H5Devices() {
  const [searchParams] = useSearchParams();
  const projectId = searchParams.get('project_id');
  const navigate = useNavigate();

  const [mode, setMode] = useState<ViewMode>(projectId ? 'cabinets' : 'projects');
  const [projects, setProjects] = useState<H5Project[]>([]);
  const [cabinets, setCabinets] = useState<H5Cabinet[]>([]);
  const [selectedProject, setSelectedProject] = useState<H5Project | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  const fetchProjects = async () => {
    setLoading(true);
    setError('');
    try {
      const res = await h5Api.getProjects();
      setProjects(res.data);
    } catch {
      setError('加载项目列表失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchCabinets = async (pid: number) => {
    setLoading(true);
    setError('');
    try {
      const res = await h5Api.getCabinets(pid);
      setCabinets(res.data);
    } catch {
      setError('加载设备列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (projectId) {
      const pid = Number(projectId);
      setMode('cabinets');
      setSelectedProject(projects.find((p) => p.id === pid) || null);
      fetchCabinets(pid);
    } else {
      setMode('projects');
      fetchProjects();
    }
    // ponytail: projects refetched on mount, ok for current scope
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [projectId]);

  const handleProjectClick = (project: H5Project) => {
    setSelectedProject(project);
    setMode('cabinets');
    navigate(`/pms/devices?project_id=${project.id}`, { replace: true });
    fetchCabinets(project.id);
  };

  const handleBack = () => {
    setMode('projects');
    setSelectedProject(null);
    setCabinets([]);
    navigate('/pms/devices', { replace: true });
  };

  if (loading) return <PageContainer title={mode === 'projects' ? '设备' : selectedProject?.name || '设备'}><Loading /></PageContainer>;
  if (error) return <PageContainer title="设备"><ErrorState message={error} onRetry={mode === 'projects' ? fetchProjects : () => selectedProject && fetchCabinets(selectedProject.id)} /></PageContainer>;

  return (
    <PageContainer
      title={mode === 'projects' ? '设备' : selectedProject?.name || '设备'}
      onBack={mode === 'cabinets' ? handleBack : undefined}
    >
      {mode === 'projects' ? (
        <div className="flex flex-col gap-2">
          {projects.length === 0 && <p className="text-center text-sm text-gray-400">暂无项目</p>}
          {projects.map((project) => (
            <button
              key={project.id}
              className="w-full rounded-xl border border-gray-200 bg-white p-4 text-left active:bg-gray-50"
              onClick={() => handleProjectClick(project)}
            >
              <span className="text-base font-medium text-gray-900">{project.name}</span>
              <svg className="float-right mt-1 h-4 w-4 text-gray-400" viewBox="0 0 24 24" fill="currentColor">
                <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" />
              </svg>
            </button>
          ))}
        </div>
      ) : (
        <div className="flex flex-col gap-2">
          {cabinets.length === 0 && <p className="text-center text-sm text-gray-400">暂无设备</p>}
          {cabinets.map((cabinet) => (
            <button
              key={cabinet.id}
              className="flex items-center justify-between rounded-xl border border-gray-200 bg-white p-4 active:bg-gray-50"
              onClick={() => navigate(`/pms/devices/${cabinet.id}`)}
            >
              <div>
                <p className="text-base font-medium text-gray-900">{cabinet.name || cabinet.abstract_id}</p>
                <p className="mt-0.5 text-xs text-gray-500">ID: {cabinet.abstract_id}</p>
              </div>
              <div className="flex items-center gap-2">
                <span className={`inline-block h-2 w-2 rounded-full ${cabinet.status === 1 ? 'bg-green-500' : 'bg-gray-400'}`} />
                <span className="text-xs text-gray-500">{cabinet.status === 1 ? '在线' : '离线'}</span>
                <svg className="h-4 w-4 text-gray-400" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" />
                </svg>
              </div>
            </button>
          ))}
        </div>
      )}
    </PageContainer>
  );
}
