/**
 * H5 共享组件：底部导航、统计卡片、通道卡片、加载/错误状态
 */
import { type ReactNode } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';

// ─── 底部导航 ───

const tabs = [
  { key: '/pms', label: '首页', icon: HomeIcon },
  { key: '/pms/devices', label: '设备', icon: DeviceIcon },
  { key: '/pms/me', label: '我的', icon: MeIcon },
];

export function BottomNav() {
  const navigate = useNavigate();
  const location = useLocation();

  const activeKey = '/' + location.pathname.split('/').slice(0, 3).join('/');

  return (
    <nav className="fixed bottom-0 left-0 right-0 z-50 flex h-14 items-center justify-around border-t border-gray-200 bg-white pb-safe">
      {tabs.map((tab) => {
        const isActive = activeKey === tab.key ||
          (tab.key === '/pms' && location.pathname === '/pms');
        return (
          <button
            key={tab.key}
            className="flex flex-1 flex-col items-center justify-center gap-0.5 py-1"
            onClick={() => navigate(tab.key)}
          >
            <tab.icon active={isActive} />
            <span className={`text-xs ${isActive ? 'font-semibold text-blue-600' : 'text-gray-500'}`}>
              {tab.label}
            </span>
          </button>
        );
      })}
    </nav>
  );
}

function HomeIcon({ active }: { active: boolean }) {
  return (
    <svg className="h-5 w-5" viewBox="0 0 24 24" fill={active ? '#2563eb' : '#9ca3af'}>
      <path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />
    </svg>
  );
}

function DeviceIcon({ active }: { active: boolean }) {
  return (
    <svg className="h-5 w-5" viewBox="0 0 24 24" fill={active ? '#2563eb' : '#9ca3af'}>
      <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z" />
    </svg>
  );
}

function MeIcon({ active }: { active: boolean }) {
  return (
    <svg className="h-5 w-5" viewBox="0 0 24 24" fill={active ? '#2563eb' : '#9ca3af'}>
      <path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
    </svg>
  );
}

// ─── 统计卡片 ───

interface StatCardProps {
  label: string;
  value: string | number;
  sub?: string;
  color?: string;
}

export function StatCard({ label, value, sub, color = 'blue' }: StatCardProps) {
  const colors: Record<string, string> = {
    blue: 'bg-blue-50 text-blue-700',
    green: 'bg-green-50 text-green-700',
    orange: 'bg-orange-50 text-orange-700',
    red: 'bg-red-50 text-red-700',
    gray: 'bg-gray-50 text-gray-700',
  };

  return (
    <div className={`flex flex-col items-center justify-center rounded-xl p-3 ${colors[color] || colors.blue}`}>
      <span className="text-2xl font-bold">{value}</span>
      <span className="mt-0.5 text-xs">{label}</span>
      {sub && <span className="mt-0.5 text-[10px] opacity-70">{sub}</span>}
    </div>
  );
}

// ─── 告警项 ───

interface AlertCardProps {
  project: string;
  cabinet: string;
  channel: number;
  alert_type: string;
}

export function AlertCard({ project, cabinet, channel, alert_type }: AlertCardProps) {
  return (
    <div className="flex items-start gap-2 rounded-lg bg-red-50 p-3 text-sm">
      <span className="mt-0.5 text-base">⚠️</span>
      <div>
        <span className="font-medium text-red-700">{project}</span>
        <span className="text-red-600"> - {cabinet} 通道{channel}</span>
        <p className="mt-0.5 text-red-500">{alert_type}</p>
      </div>
    </div>
  );
}

// ─── 项目卡片 ───

interface ProjectCardProps {
  name: string;
  cabinet_count: number;
  charging: number;
  idle: number;
  fault: number;
  onClick: () => void;
}

export function ProjectCard({ name, cabinet_count, charging, idle, fault, onClick }: ProjectCardProps) {
  return (
    <button className="w-full rounded-xl border border-gray-200 bg-white p-4 text-left active:bg-gray-50" onClick={onClick}>
      <div className="flex items-center justify-between">
        <span className="text-base font-semibold text-gray-900">{name}</span>
        <span className="text-xs text-gray-500">{cabinet_count}柜</span>
      </div>
      <div className="mt-2 flex gap-3 text-xs">
        <span className="text-green-600">充电{charging}</span>
        <span className="text-gray-500">空闲{idle}</span>
        {fault > 0 && <span className="text-red-600">故障{fault}</span>}
      </div>
    </button>
  );
}

// ─── 通道卡片 ───

interface ChannelCardProps {
  channelId: number;
  status: number;        // 0=空闲 1=充电中 2=故障 3=离线
  voltage?: number;
  current?: number;
  onClick: () => void;
}

const statusConfig: Record<number, { label: string; bg: string; dot: string }> = {
  0: { label: '空闲', bg: 'bg-gray-50', dot: 'bg-gray-400' },
  1: { label: '充电中', bg: 'bg-green-50', dot: 'bg-green-500' },
  2: { label: '故障', bg: 'bg-red-50', dot: 'bg-red-500' },
  3: { label: '离线', bg: 'bg-gray-100', dot: 'bg-gray-400' },
};

export function ChannelCard({ channelId, status, voltage, current, onClick }: ChannelCardProps) {
  const cfg = statusConfig[status] || statusConfig[3];

  return (
    <button className={`flex flex-col items-center rounded-lg p-2.5 ${cfg.bg} active:opacity-70`} onClick={onClick}>
      <span className="text-xs font-medium text-gray-700">通道{channelId}</span>
      <span className={`mt-1 inline-block h-2 w-2 rounded-full ${cfg.dot}`} />
      <span className="mt-0.5 text-[10px] text-gray-500">{cfg.label}</span>
      {voltage !== undefined && (
        <span className="mt-0.5 text-[10px] text-gray-400">{voltage.toFixed(1)}V</span>
      )}
      {current !== undefined && (
        <span className="text-[10px] text-gray-400">{current.toFixed(1)}A</span>
      )}
    </button>
  );
}

// ─── 加载状态 ───

export function Loading() {
  return (
    <div className="flex h-40 items-center justify-center">
      <div className="h-6 w-6 animate-spin rounded-full border-2 border-blue-600 border-t-transparent" />
      <span className="ml-2 text-sm text-gray-500">加载中...</span>
    </div>
  );
}

// ─── 错误状态 ───

export function ErrorState({ message, onRetry }: { message: string; onRetry?: () => void }) {
  return (
    <div className="flex flex-col items-center justify-center gap-3 py-16">
      <span className="text-4xl">😵</span>
      <p className="text-sm text-gray-500">{message}</p>
      {onRetry && (
        <button className="rounded-lg bg-blue-600 px-4 py-2 text-sm text-white" onClick={onRetry}>
          重试
        </button>
      )}
    </div>
  );
}

// ─── 页面容器 ───

export function PageContainer({ children, title, onBack }: { children: ReactNode; title?: string; onBack?: () => void }) {
  return (
    <div className="flex min-h-screen flex-col bg-gray-50 pb-16">
      {title && (
        <header className="flex items-center gap-2 border-b border-gray-200 bg-white px-4 py-3">
          {onBack && (
            <button className="text-lg text-gray-600" onClick={onBack}>
              <svg className="h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
                <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" />
              </svg>
            </button>
          )}
          <h1 className="text-base font-semibold text-gray-900">{title}</h1>
        </header>
      )}
      <div className="flex-1 px-4 py-4">{children}</div>
    </div>
  );
}

// ─── 确认弹窗 ───

export function ConfirmDialog({ open, title, message, onConfirm, onCancel }: {
  open: boolean;
  title: string;
  message: string;
  onConfirm: () => void;
  onCancel: () => void;
}) {
  if (!open) return null;
  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40" onClick={onCancel}>
      <div className="mx-4 w-full max-w-xs rounded-xl bg-white p-5" onClick={(e) => e.stopPropagation()}>
        <h3 className="text-center text-base font-semibold text-gray-900">{title}</h3>
        <p className="mt-2 text-center text-sm text-gray-500">{message}</p>
        <div className="mt-5 flex gap-3">
          <button className="flex-1 rounded-lg border border-gray-300 py-2 text-sm text-gray-700" onClick={onCancel}>取消</button>
          <button className="flex-1 rounded-lg bg-blue-600 py-2 text-sm text-white" onClick={onConfirm}>确认</button>
        </div>
      </div>
    </div>
  );
}
