/**
 * H5 首页 Dashboard
 * - 统计卡片（在线/充电中/空闲/故障）
 * - 今日统计
 * - 告警通知
 * - 项目列表
 */
import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { h5Api, type DashboardData } from '../api';
import { StatCard, AlertCard, ProjectCard, Loading, ErrorState } from '../components';

export default function H5Home() {
  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const navigate = useNavigate();

  const fetchData = async () => {
    setLoading(true);
    setError('');
    try {
      const res = await h5Api.getDashboard();
      setData(res.data);
    } catch {
      setError('加载失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
    // ponytail: 30s auto-refresh, add WebSocket if real-time needed
  }, []);

  if (loading) return <Loading />;
  if (error) return <ErrorState message={error} onRetry={fetchData} />;
  if (!data) return null;

  return (
    <div className="flex flex-col gap-4">
      {/* 统计卡片 */}
      <section>
        <h2 className="mb-3 text-base font-semibold text-gray-900">设备概览</h2>
        <div className="grid grid-cols-4 gap-2">
          <StatCard label="在线" value={data.online_cabinets} sub="柜子" color="blue" />
          <StatCard label="充电中" value={data.charging_count} sub="柜子" color="green" />
          <StatCard label="空闲" value={data.idle_channels} sub="通道" color="gray" />
          <StatCard label="故障" value={data.fault_channels} sub="通道" color="red" />
        </div>
      </section>

      {/* 今日统计 */}
      <section className="rounded-xl bg-white p-4">
        <h2 className="mb-3 text-base font-semibold text-gray-900">今日统计</h2>
        <div className="flex justify-around text-center">
          <div>
            <p className="text-xl font-bold text-blue-600">{data.today_charge_count}</p>
            <p className="text-xs text-gray-500">充电次数</p>
          </div>
          <div className="w-px bg-gray-200" />
          <div>
            <p className="text-xl font-bold text-blue-600">{data.today_charge_hours}</p>
            <p className="text-xs text-gray-500">充电时长(h)</p>
          </div>
          <div className="w-px bg-gray-200" />
          <div>
            <p className="text-xl font-bold text-blue-600">{data.today_energy_kwh.toLocaleString()}</p>
            <p className="text-xs text-gray-500">能耗(kWh)</p>
          </div>
        </div>
      </section>

      {/* 告警通知 */}
      {data.alerts.length > 0 && (
        <section>
          <h2 className="mb-3 text-base font-semibold text-gray-900">告警通知</h2>
          <div className="flex flex-col gap-2">
            {data.alerts.map((alert, i) => (
              <AlertCard key={i} {...alert} />
            ))}
          </div>
        </section>
      )}

      {/* 项目列表 */}
      <section>
        <h2 className="mb-3 text-base font-semibold text-gray-900">项目列表</h2>
        <div className="flex flex-col gap-2">
          {data.projects.map((project) => (
            <ProjectCard
              key={project.id}
              {...project}
              onClick={() => navigate(`/pms/devices?project_id=${project.id}`)}
            />
          ))}
        </div>
      </section>
    </div>
  );
}
