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

// 网站状态卡片组件
export default function WebsiteCard({ website, onRefresh, onEdit, onDelete }) {
  const [expanded, setExpanded] = useState(false);
  
  // 获取第一个URL的状态作为主状态
  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;
  
  return (
    <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden hover:shadow-md transition-shadow">
      {/* 卡片头部 */}
      <div 
        className="p-3 cursor-pointer"
        onClick={() => setExpanded(!expanded)}
      >
        {/* 第一行：图标、名称、状态 */}
        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center space-x-2 min-w-0 flex-1">
            {/* Favicon */}
            <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">
              {website.website?.favicon ? (
                <img 
                  src={website.website.favicon} 
                  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 ${website.website?.favicon ? 'hidden' : ''}`}
                style={{ display: website.website?.favicon ? 'none' : 'flex' }}
              >
                {website.website?.name?.[0] || '?'}
              </span>
            </div>
            
            {/* 网站名称 */}
            <h3 className="font-semibold text-gray-800 truncate">
              {website.website?.name || '未知网站'}
            </h3>
          </div>
          
          {/* 展开箭头 */}
          <svg 
            className={`w-4 h-4 text-gray-400 transform transition-transform flex-shrink-0 ${expanded ? 'rotate-180' : ''}`}
            fill="none" 
            stroke="currentColor" 
            viewBox="0 0 24 24"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
          </svg>
        </div>
        
        {/* 第二行：状态、延迟、访问按钮 */}
        <div className="flex items-center justify-between mb-2">
          <div className="flex items-center space-x-2">
            {/* 状态徽章 */}
            <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${getStatusColor(isUp, statusCode)}`}>
              {isUp ? `${statusCode}` : '离线'}
            </span>
            
            {/* 延迟 */}
            <span className={`text-xs font-medium ${getLatencyColor(latency)}`}>
              {formatLatency(latency)}
            </span>
          </div>

          {/* 访问按钮 */}
          <button
            onClick={(e) => {
              e.stopPropagation();
              if (primaryUrl) {
                window.open(primaryUrl, '_blank', 'noopener,noreferrer');
              }
            }}
            disabled={!primaryUrl}
            className={`flex items-center space-x-1 px-2.5 py-1 text-xs font-medium rounded-full transition-all flex-shrink-0 ${
              primaryUrl
                ? 'text-white bg-gradient-to-r from-emerald-500 to-green-500 hover:from-emerald-600 hover:to-green-600 shadow-sm hover:shadow'
                : 'text-gray-400 bg-gray-100 cursor-not-allowed'
            }`}
          >
            <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>
        
        {/* 网站描述 */}
        <p className="text-xs text-gray-500 truncate mb-2">
          {website.website?.title || website.website?.urls?.[0]?.url || '-'}
        </p>
        
        {/* 可用率条 */}
        <div className="mt-3">
          <div className="flex justify-between text-xs text-gray-500 mb-1">
            <span>24h可用率</span>
            <span className={getUptimeColor(website.uptime_24h || 0)}>
              {formatUptime(website.uptime_24h)}
            </span>
          </div>
          <div className="h-2 bg-gray-100 rounded-full overflow-hidden">
            <div 
              className="h-full bg-gradient-to-r from-emerald-400 to-green-500 rounded-full transition-all"
              style={{ width: `${Math.min(website.uptime_24h || 0, 100)}%` }}
            />
          </div>
        </div>
      </div>
      
      {/* 展开详情 */}
      {expanded && (
        <div className="border-t border-gray-100 bg-gray-50 p-4">
          {/* URL列表 */}
          <div className="space-y-3">
            {website.url_statuses?.map((urlStatus, index) => (
              <div 
                key={urlStatus.url_info?.id || index}
                className="bg-white rounded-lg p-3 border border-gray-100"
              >
                <div className="flex items-center justify-between mb-2">
                  <span className="text-sm text-gray-600 truncate flex-1 mr-2">
                    {urlStatus.url_info?.url}
                  </span>
                  <span className={`px-2 py-0.5 rounded text-xs 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 className="grid grid-cols-3 gap-2 text-xs">
                  <div>
                    <span className="text-gray-400">延迟</span>
                    <p className={`font-medium ${getLatencyColor(urlStatus.current_state?.latency)}`}>
                      {formatLatency(urlStatus.current_state?.latency)}
                    </p>
                  </div>
                  <div>
                    <span className="text-gray-400">24h</span>
                    <p className={`font-medium ${getUptimeColor(urlStatus.uptime_24h)}`}>
                      {formatUptime(urlStatus.uptime_24h)}
                    </p>
                  </div>
                  <div>
                    <span className="text-gray-400">7d</span>
                    <p className={`font-medium ${getUptimeColor(urlStatus.uptime_7d)}`}>
                      {formatUptime(urlStatus.uptime_7d)}
                    </p>
                  </div>
                </div>
              </div>
            ))}
          </div>
          
          {/* 操作按钮 */}
          <div className="flex justify-end space-x-2 mt-4">
            <button
              onClick={(e) => {
                e.stopPropagation();
                onRefresh?.(website.website?.id);
              }}
              className="px-3 py-1.5 text-xs font-medium text-emerald-600 bg-emerald-50 rounded-lg hover:bg-emerald-100 transition-colors"
            >
              立即检测
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                onEdit?.(website);
              }}
              className="px-3 py-1.5 text-xs font-medium text-gray-600 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors"
            >
              编辑
            </button>
            <button
              onClick={(e) => {
                e.stopPropagation();
                if (confirm('确定要删除这个网站吗？')) {
                  onDelete?.(website.website?.id);
                }
              }}
              className="px-3 py-1.5 text-xs font-medium text-red-600 bg-red-50 rounded-lg hover:bg-red-100 transition-colors"
            >
              删除
            </button>
          </div>
          
          {/* 最后检测时间 */}
          <div className="text-xs text-gray-400 text-right mt-2">
            最后检测: {formatTime(website.last_checked)}
          </div>
        </div>
      )}
    </div>
  );
}
