import { useState, useMemo } from 'react';
import { formatLatency, formatUptime, formatTime, getStatusColor, getUptimeColor, getLatencyColor } from '../hooks/useMonitor';

const HISTORY_DAYS = 90;

const INTRANET_FALLBACK_ICON =
  'https://api.iconify.design/mdi/lan-connect.svg?color=%23059669';
const FAVICON_PROXY_BASE = 'https://favicon.smyhub.com/api/favicon?url=';

function getBarColor(bar) {
  if (bar.uptime === null) return 'bg-gray-200';
  if (bar.uptime >= 99) return 'bg-emerald-400';
  if (bar.uptime >= 95) return 'bg-yellow-400';
  if (bar.uptime >= 80) return 'bg-orange-400';
  return 'bg-red-500';
}

function getBarHoverColor(bar) {
  if (bar.uptime === null) return 'hover:bg-gray-300';
  if (bar.uptime >= 99) return 'hover:bg-emerald-500';
  if (bar.uptime >= 95) return 'hover:bg-yellow-500';
  if (bar.uptime >= 80) return 'hover:bg-orange-500';
  return 'hover:bg-red-600';
}

export default function WebsiteCard({ website, onRefresh, onEdit, onDelete, readOnly = false }) {
  const [expanded, setExpanded] = useState(false);
  const [hoveredBar, setHoveredBar] = useState(null);

  const primaryStatus = website.url_statuses?.[0];
  const isUp = primaryStatus?.current_state?.is_up ?? false;
  const statusCode = primaryStatus?.current_state?.status_code ?? 0;
  const latency = primaryStatus?.current_state?.latency ?? 0;
  const primaryUrl = website.website?.urls?.[0]?.url || website.url_statuses?.[0]?.url_info?.url;
  const isIntranet = website.is_intranet === true;
  const cardIconSrc = isIntranet
    ? (website.website?.favicon || INTRANET_FALLBACK_ICON)
    : (primaryUrl ? `${FAVICON_PROXY_BASE}${encodeURIComponent(primaryUrl)}` : null);

  const dailyBars = useMemo(() => {
    const bars = [];
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    const statsMap = {};
    (website.daily_history || []).forEach(stat => {
      const d = new Date(stat.date);
      const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
      statsMap[key] = stat;
    });

    for (let i = HISTORY_DAYS - 1; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(date.getDate() - i);
      const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      const stat = statsMap[key];
      bars.push({
        date: key,
        uptime: stat ? stat.uptime : null,
        totalCount: stat?.total_count ?? 0,
        avgLatency: stat?.avg_latency ?? 0,
      });
    }

    return bars;
  }, [website.daily_history]);

  const statusDisplay = (() => {
    if (!primaryStatus?.current_state?.checked_at || primaryStatus.current_state.checked_at === '0001-01-01T00:00:00Z') {
      return { text: '等待检测', color: 'text-gray-400' };
    }
    if (isUp) {
      return { text: '运行正常', color: 'text-emerald-500' };
    }
    return { text: '服务异常', color: 'text-red-500' };
  })();

  const uptime90d = website.uptime_90d;
  const hasUptimeData = uptime90d != null && uptime90d > 0;

  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-md transition-shadow">
      {/* 主体区域 */}
      <div
        className="p-3 sm:p-4 cursor-pointer select-none"
        onClick={() => setExpanded(!expanded)}
      >
        {/* 头部：图标 + 名称 + 状态 + 访问按钮 */}
        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center space-x-2.5 min-w-0 flex-1">
            <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-green-50 to-emerald-100 flex items-center justify-center overflow-hidden flex-shrink-0">
              {cardIconSrc ? (
                <img
                  src={cardIconSrc}
                  alt=""
                  className="w-7 h-7 object-contain drop-shadow"
                  onError={(e) => {
                    e.target.style.display = 'none';
                    e.target.nextSibling.style.display = 'flex';
                  }}
                />
              ) : null}
              <span
                className={`text-base font-bold text-emerald-600 ${cardIconSrc ? 'hidden' : ''}`}
                style={{ display: cardIconSrc ? 'none' : 'flex' }}
              >
                {website.website?.name?.[0] || '?'}
              </span>
            </div>
            <div className="min-w-0 flex-1">
              <h3 className="font-semibold text-gray-800 truncate">
                {website.website?.name || '未知网站'}
              </h3>
              <span className={`text-xs font-medium ${statusDisplay.color}`}>
                {statusDisplay.text}
              </span>
            </div>
          </div>
          {primaryUrl && (
            <button
              onClick={(e) => {
                e.stopPropagation();
                window.open(primaryUrl, '_blank', 'noopener,noreferrer');
              }}
              className="flex items-center space-x-1 px-2.5 py-1 text-xs font-medium text-white bg-gradient-to-r from-emerald-500 to-green-500 rounded-full hover:from-emerald-600 hover:to-green-600 transition-all shadow-sm hover:shadow flex-shrink-0 ml-2"
            >
              <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
              </svg>
              <span>访问</span>
            </button>
          )}
        </div>

        {/* 90 天可用率竖条图 */}
        <div className="relative">
          <div className="flex items-stretch gap-[1px] h-[26px]">
            {dailyBars.map((bar, i) => (
              <div
                key={i}
                className={`flex-1 rounded-[1px] transition-colors ${getBarColor(bar)} ${getBarHoverColor(bar)}`}
                onMouseEnter={() => setHoveredBar(i)}
                onMouseLeave={() => setHoveredBar(null)}
              />
            ))}
          </div>

          {/* 悬浮提示 */}
          {hoveredBar !== null && dailyBars[hoveredBar] && (
            <div
              className="absolute -top-10 px-2 py-1 bg-gray-800 text-white text-[10px] rounded shadow-lg whitespace-nowrap pointer-events-none z-10"
              style={{
                left: `${(hoveredBar / HISTORY_DAYS) * 100}%`,
                transform: 'translateX(-50%)',
              }}
            >
              {dailyBars[hoveredBar].date}
              {' · '}
              {dailyBars[hoveredBar].uptime !== null
                ? `${dailyBars[hoveredBar].uptime.toFixed(1)}%`
                : '无数据'}
            </div>
          )}
        </div>

        {/* 底部标签 */}
        <div className="flex justify-between items-center text-[10px] text-gray-400 mt-1.5">
          <span>{HISTORY_DAYS} 天前</span>
          <span className="font-medium text-gray-500">
            {hasUptimeData ? `${uptime90d.toFixed(2)}% 可用率` : '-'}
          </span>
          <span>今天</span>
        </div>

        {/* 状态 / 延迟 / 24h */}
        <div className="flex items-center gap-3 mt-2 text-[10px]">
          <span className="text-gray-400">状态 <span className={`font-semibold ${getStatusColor(isUp, statusCode)}`}>{isUp ? statusCode : '离线'}</span></span>
          <span className="text-gray-400">延迟 <span className={`font-semibold ${getLatencyColor(latency)}`}>{formatLatency(latency)}</span></span>
          <span className="text-gray-400">24h <span className={`font-semibold ${getUptimeColor(website.uptime_24h || 0)}`}>{formatUptime(website.uptime_24h)}</span></span>
        </div>

        {/* IP 地址（IPv4 / IPv6 分开显示） */}
        {!isIntranet && website.website?.ip_addresses?.length > 0 && (() => {
          const ipv4 = website.website.ip_addresses.filter(ip => !ip.includes(':'));
          const ipv6 = website.website.ip_addresses.filter(ip => ip.includes(':'));
          return (ipv4.length > 0 || ipv6.length > 0) && (
            <div className="mt-2 space-y-1">
              {ipv4.length > 0 && (
                <div className="flex items-center gap-1.5 flex-wrap">
                  <span className="text-[10px] text-gray-400 w-7 flex-shrink-0">IPv4</span>
                  {ipv4.map((ip, i) => (
                    <span key={i} className="px-1.5 py-0.5 bg-gray-50 text-gray-600 rounded text-[10px] font-mono">{ip}</span>
                  ))}
                </div>
              )}
              {ipv6.length > 0 && (
                <div className="flex items-center gap-1.5 flex-wrap">
                  <span className="text-[10px] text-gray-400 w-7 flex-shrink-0">IPv6</span>
                  {ipv6.map((ip, i) => (
                    <span key={i} className="px-1.5 py-0.5 bg-gray-50 text-gray-600 rounded text-[10px] font-mono truncate max-w-full">{ip}</span>
                  ))}
                </div>
              )}
            </div>
          );
        })()}
      </div>

      {/* 展开详情 */}
      {expanded && (
        <div className="border-t border-gray-100 bg-gray-50/80 p-3 sm:p-4">
          {/* URL 列表 */}
          <div className="space-y-2">
            {website.url_statuses?.map((urlStatus, index) => (
              <div
                key={urlStatus.url_info?.id || index}
                className="bg-white rounded-lg p-2.5 border border-gray-100"
              >
                <div className="flex items-center justify-between">
                  <span className="text-xs text-gray-600 truncate flex-1 mr-2">
                    {urlStatus.url_info?.url}
                  </span>
                  <span className={`px-1.5 py-0.5 rounded text-[10px] font-medium ${
                    getStatusColor(urlStatus.current_state?.is_up, urlStatus.current_state?.status_code)
                  }`}>
                    {urlStatus.current_state?.is_up ? urlStatus.current_state?.status_code : '离线'}
                  </span>
                </div>
              </div>
            ))}
          </div>

          {/* 操作按钮（仅管理后台） */}
          <div className={`flex items-center mt-3 ${readOnly ? 'justify-start' : 'justify-between'}`}>
            <span className="text-[10px] text-gray-400">
              {formatTime(website.last_checked)}
            </span>
            {!readOnly && (
              <div className="flex space-x-1.5">
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation();
                    onRefresh?.(website.website?.id);
                  }}
                  className="px-2.5 py-1 text-[10px] font-medium text-emerald-600 bg-emerald-50 rounded-md hover:bg-emerald-100 transition-colors"
                >
                  检测
                </button>
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation();
                    onEdit?.(website);
                  }}
                  className="px-2.5 py-1 text-[10px] font-medium text-gray-600 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors"
                >
                  编辑
                </button>
                <button
                  type="button"
                  onClick={(e) => {
                    e.stopPropagation();
                    if (confirm('确定要删除这个网站吗？')) {
                      onDelete?.(website.website?.id);
                    }
                  }}
                  className="px-2.5 py-1 text-[10px] font-medium text-red-600 bg-red-50 rounded-md hover:bg-red-100 transition-colors"
                >
                  删除
                </button>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}
