/**
 * H5 通道详情
 * - 实时状态（SOC/SOH）
 * - 电气参数（电压/电流/功率/能耗）
 * - BMS数据（单体电压/温度/告警）
 * - 充电曲线（示意）
 * - 操作按钮（停止充电、开门）
 */
import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { h5Api, type CompartmentDetail } from '../api';
import { Loading, ErrorState, PageContainer, ConfirmDialog } from '../components';

export default function H5CompartmentDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [data, setData] = useState<CompartmentDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [actionLoading, setActionLoading] = useState('');
  const [confirmAction, setConfirmAction] = useState<'stop' | 'door' | null>(null);

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

  useEffect(() => {
    fetchDetail();
    // ponytail: 15s auto-refresh during charging, add WebSocket for real-time
    const timer = setInterval(fetchDetail, 15000);
    return () => clearInterval(timer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  const handleAction = async (action: 'start' | 'stop' | 'door') => {
    if (!id || actionLoading) return;
    setActionLoading(action);
    try {
      if (action === 'start') {
        await h5Api.startCharge(Number(id));
      } else if (action === 'stop') {
        await h5Api.stopCharge(Number(id));
      } else if (action === 'door') {
        await h5Api.openDoor(Number(id));
      }
      setConfirmAction(null);
      fetchDetail();
    } catch {
      setError('操作失败，请重试');
    } finally {
      setActionLoading('');
    }
  };

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

  const statusLabel: Record<number, string> = { 0: '空闲', 1: '充电中', 2: '故障', 3: '离线' };
  const isCharging = data.status === 1;
  const isIdle = data.status === 0;

  return (
    <PageContainer title={`通道${data.channel_id}`} onBack={() => navigate(-1)}>
      {/* 实时状态 */}
      <section className="mb-4 rounded-xl bg-white p-4">
        <div className="flex items-center justify-between">
          <h3 className="text-base font-semibold text-gray-900">实时状态</h3>
          <span className={`rounded-full px-3 py-1 text-xs font-medium ${
            data.status === 1 ? 'bg-green-100 text-green-700' :
            data.status === 0 ? 'bg-gray-100 text-gray-500' :
            'bg-red-100 text-red-700'
          }`}>
            {statusLabel[data.status] || '未知'}
          </span>
        </div>
        <div className="mt-4 grid grid-cols-3 gap-4 text-center">
          <div>
            <p className="text-lg font-bold text-blue-600">{data.soc ?? '-'}%</p>
            <p className="text-xs text-gray-500">SOC</p>
          </div>
          <div>
            <p className="text-lg font-bold text-blue-600">{data.soh ?? '-'}%</p>
            <p className="text-xs text-gray-500">SOH</p>
          </div>
          <div>
            <p className="text-lg font-bold text-blue-600">{data.energy?.toFixed(1) ?? '-'}</p>
            <p className="text-xs text-gray-500">能耗(kWh)</p>
          </div>
        </div>
      </section>

      {/* 电气参数 */}
      <section className="mb-4 rounded-xl bg-white p-4">
        <h3 className="mb-3 text-base font-semibold text-gray-900">电气参数</h3>
        <div className="grid grid-cols-2 gap-y-3 text-sm">
          <div className="flex justify-between pr-4">
            <span className="text-gray-500">电压</span>
            <span className="font-medium text-gray-900">{data.voltage?.toFixed(1) ?? '-'} V</span>
          </div>
          <div className="flex justify-between pl-4">
            <span className="text-gray-500">电流</span>
            <span className="font-medium text-gray-900">{data.current?.toFixed(1) ?? '-'} A</span>
          </div>
          <div className="flex justify-between pr-4">
            <span className="text-gray-500">功率</span>
            <span className="font-medium text-gray-900">{data.power?.toFixed(1) ?? '-'} W</span>
          </div>
          <div className="flex justify-between pl-4">
            <span className="text-gray-500">能耗</span>
            <span className="font-medium text-gray-900">{data.energy?.toFixed(3) ?? '-'} kWh</span>
          </div>
        </div>
      </section>

      {/* BMS 数据 */}
      {data.cell_voltages && data.cell_voltages.length > 0 && (
        <section className="mb-4 rounded-xl bg-white p-4">
          <h3 className="mb-3 text-base font-semibold text-gray-900">BMS 数据</h3>
          {/* 单体电压 */}
          <div className="mb-3">
            <p className="mb-1 text-xs text-gray-500">单体电压 (V)</p>
            <div className="flex flex-wrap gap-1">
              {data.cell_voltages.map((v, i) => (
                <span key={i} className="rounded bg-blue-50 px-2 py-0.5 text-xs text-blue-700">
                  #{i + 1}: {v.toFixed(3)}
                </span>
              ))}
            </div>
          </div>
          {/* 单体温度 */}
          {data.cell_temps && data.cell_temps.length > 0 && (
            <div className="mb-3">
              <p className="mb-1 text-xs text-gray-500">温度 (°C)</p>
              <div className="flex flex-wrap gap-1">
                {data.cell_temps.map((t, i) => (
                  <span key={i} className={`rounded px-2 py-0.5 text-xs ${t > 50 ? 'bg-red-50 text-red-700' : 'bg-orange-50 text-orange-700'}`}>
                    #{i + 1}: {t.toFixed(1)}
                  </span>
                ))}
              </div>
            </div>
          )}
          {/* BMS 告警 */}
          {data.bms_alerts && data.bms_alerts.length > 0 && (
            <div>
              <p className="mb-1 text-xs text-red-500">告警</p>
              <ul className="list-inside list-disc text-xs text-red-600">
                {data.bms_alerts.map((alert, i) => (
                  <li key={i}>{alert}</li>
                ))}
              </ul>
            </div>
          )}
        </section>
      )}

      {/* 充电曲线示意 */}
      {isCharging && (
        <section className="mb-4 rounded-xl bg-white p-4">
          <h3 className="mb-3 text-base font-semibold text-gray-900">充电曲线</h3>
          {/* TODO: 待后端提供充电曲线API后替换为真实数据 */}
          <div className="flex h-24 items-end gap-1">
            {[30, 45, 55, 50, 65, 70, 75, 72, 80, 85, 82, 88].map((h, i) => (
              <div key={i} className="flex-1 rounded-t bg-blue-500" style={{ height: `${h}%` }} title={`${h}%`} />
            ))}
          </div>
          <div className="mt-1 flex justify-between text-[10px] text-gray-400">
            <span>12:00</span>
            <span>当前</span>
          </div>
          {/* ponytail: static mock chart, replace with real chart lib when backend provides data */}
        </section>
      )}

      {/* 充电记录 */}
      {data.charge_records && data.charge_records.length > 0 && (
        <section className="mb-4 rounded-xl bg-white p-4">
          <h3 className="mb-3 text-base font-semibold text-gray-900">充电记录</h3>
          <div className="flex flex-col gap-2">
            {data.charge_records.slice(0, 5).map((record) => (
              <div key={record.id} className="flex items-center justify-between text-sm">
                <div>
                  <p className="text-gray-900">{record.start_time.slice(0, 16)}</p>
                  {record.end_time && <p className="text-xs text-gray-400">{record.end_time.slice(0, 16)}</p>}
                </div>
                <div className="text-right">
                  <p className="text-gray-900">{record.energy_kwh.toFixed(2)} kWh</p>
                  <p className="text-xs text-gray-400">¥{record.cost.toFixed(2)}</p>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}

      {/* 操作按钮 */}
      <div className="flex flex-col gap-3 pb-4">
        {isIdle && (
          <button
            className="w-full rounded-lg bg-green-600 py-3 text-base font-medium text-white disabled:opacity-50"
            disabled={!!actionLoading}
            onClick={() => handleAction('start')}
          >
            {actionLoading === 'start' ? '操作中...' : '开始充电'}
          </button>
        )}
        {isCharging && (
          <button
            className="w-full rounded-lg bg-orange-500 py-3 text-base font-medium text-white disabled:opacity-50"
            disabled={!!actionLoading}
            onClick={() => setConfirmAction('stop')}
          >
            {actionLoading === 'stop' ? '操作中...' : '停止充电'}
          </button>
        )}
        <button
          className="w-full rounded-lg border border-gray-300 bg-white py-3 text-base font-medium text-gray-700 disabled:opacity-50"
          disabled={!!actionLoading}
          onClick={() => setConfirmAction('door')}
        >
          {actionLoading === 'door' ? '操作中...' : '开门'}
        </button>
      </div>

      {/* 确认弹窗 */}
      <ConfirmDialog
        open={confirmAction === 'stop'}
        title="停止充电"
        message="确定要停止当前充电？"
        onConfirm={() => handleAction('stop')}
        onCancel={() => setConfirmAction(null)}
      />
      <ConfirmDialog
        open={confirmAction === 'door'}
        title="开门"
        message="确定要打开仓门？"
        onConfirm={() => handleAction('door')}
        onCancel={() => setConfirmAction(null)}
      />
    </PageContainer>
  );
}
