import { useState, useCallback, useMemo } from 'react';
import WebsiteCard from '../components/WebsiteCard';
import WebsiteModal from '../components/WebsiteModal';
import StatsCard from '../components/StatsCard';
import { useAutoRefresh } from '../hooks/useMonitor';
import { getWebsites, deleteWebsite, checkWebsiteNow, getGroups } from '../services/api';

export default function Dashboard() {
  const [modalOpen, setModalOpen] = useState(false);
  const [editData, setEditData] = useState(null);
  const [selectedGroup, setSelectedGroup] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');

  // 获取网站数据
  const fetchData = useCallback(() => getWebsites(), []);
  const { data: websites, loading, error, refresh } = useAutoRefresh(fetchData, 30000);

  // 获取分组数据
  const fetchGroups = useCallback(() => getGroups(), []);
  const { data: groups } = useAutoRefresh(fetchGroups, 60000);

  // 处理添加网站
  const handleAdd = () => {
    setEditData(null);
    setModalOpen(true);
  };

  // 处理编辑网站
  const handleEdit = (website) => {
    setEditData(website);
    setModalOpen(true);
  };


  // 处理删除网站
  const handleDelete = async (id) => {
    try {
      await deleteWebsite(id);
      refresh();
    } catch (err) {
      alert('删除失败: ' + err.message);
    }
  };

  // 处理立即检测
  const handleRefresh = async (id) => {
    try {
      await checkWebsiteNow(id);
      setTimeout(refresh, 2000); // 2秒后刷新数据
    } catch (err) {
      alert('检测失败: ' + err.message);
    }
  };

  // 按分组和搜索过滤网站
  const filteredWebsites = useMemo(() => {
    if (!websites) return [];
    
    return websites.filter(site => {
      // 分组过滤（支持多分组）
      if (selectedGroup !== 'all') {
        const siteGroups = site.website?.groups || (site.website?.group ? [site.website.group] : []);
        if (!siteGroups.includes(selectedGroup)) {
          return false;
        }
      }
      // 搜索过滤
      if (searchTerm) {
        const term = searchTerm.toLowerCase();
        return (
          site.website?.name?.toLowerCase().includes(term) ||
          site.website?.title?.toLowerCase().includes(term) ||
          site.website?.urls?.some(u => u.url.toLowerCase().includes(term))
        );
      }
      return true;
    });
  }, [websites, selectedGroup, searchTerm]);

  // 按分组分类网站（一个网站可出现在多个分组下）
  const groupedWebsites = useMemo(() => {
    const grouped = {};
    
    filteredWebsites.forEach(site => {
      const siteGroups = site.website?.groups || (site.website?.group ? [site.website.group] : ['normal']);
      siteGroups.forEach(groupId => {
        if (selectedGroup !== 'all' && groupId !== selectedGroup) return;
        if (!grouped[groupId]) {
          grouped[groupId] = [];
        }
        grouped[groupId].push(site);
      });
    });
    
    return grouped;
  }, [filteredWebsites, selectedGroup]);

  // 获取分组名称
  const getGroupName = (groupId) => {
    const group = groups?.find(g => g.id === groupId);
    return group?.name || groupId;
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-emerald-50 via-green-50 to-teal-50">
      {/* 顶部导航 */}
      <header className="bg-white/80 backdrop-blur-md shadow-sm sticky top-0 z-40">
        <div className="max-w-screen-2xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            {/* Logo */}
            <div className="flex items-center space-x-3">
              <div className="w-10 h-10 rounded-xl overflow-hidden shadow-lg shadow-emerald-200">
                <img
                  src="/logo.png"
                  alt="萌芽Ping"
                  className="w-full h-full object-cover"
                />
              </div>
              <div>
                <h1 className="text-xl font-bold bg-gradient-to-r from-emerald-600 to-green-600 bg-clip-text text-transparent">
                  萌芽Ping
                </h1>
                <p className="text-xs text-gray-500">网站监控面板</p>
              </div>
            </div>
            
            {/* 添加按钮 */}
            <button
              onClick={handleAdd}
              className="flex items-center px-4 py-2 bg-gradient-to-r from-emerald-500 to-green-500 text-white rounded-lg hover:from-emerald-600 hover:to-green-600 transition-all shadow-md shadow-emerald-200"
            >
              <svg className="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
              <span className="hidden sm:inline">添加监控</span>
            </button>
          </div>
        </div>
      </header>

      {/* 主内容区 */}
      <main className="max-w-screen-2xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        {/* 统计概览 */}
        <section className="mb-6">
          <StatsCard websites={websites} />
        </section>

        {/* 过滤和搜索 */}
        <section className="mb-6">
          <div className="flex flex-col sm:flex-row gap-4">
            {/* 分组选择 */}
            <div className="flex items-center space-x-2 overflow-x-auto pb-2 sm:pb-0">
              <button
                onClick={() => setSelectedGroup('all')}
                className={`px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-all ${
                  selectedGroup === 'all'
                    ? 'bg-emerald-500 text-white shadow-md shadow-emerald-200'
                    : 'bg-white text-gray-600 hover:bg-gray-50'
                }`}
              >
                全部
              </button>
              {groups?.map(group => (
                <button
                  key={group.id}
                  onClick={() => setSelectedGroup(group.id)}
                  className={`px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-all ${
                    selectedGroup === group.id
                      ? 'bg-emerald-500 text-white shadow-md shadow-emerald-200'
                      : 'bg-white text-gray-600 hover:bg-gray-50'
                  }`}
                >
                  {group.name}
                </button>
              ))}
            </div>
            
            {/* 搜索框 */}
            <div className="flex-1 sm:max-w-xs">
              <div className="relative">
                <svg className="absolute left-3 top-1/2 transform -translate-y-1/2 w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
                <input
                  type="text"
                  placeholder="搜索网站..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-emerald-500 focus:border-transparent outline-none transition-all"
                />
              </div>
            </div>
          </div>
        </section>

        {/* 网站列表 */}
        <section>
          {loading && !websites ? (
            <div className="flex items-center justify-center py-12">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-emerald-500"></div>
              <span className="ml-3 text-gray-500">加载中...</span>
            </div>
          ) : error ? (
            <div className="text-center py-12">
              <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-red-100 flex items-center justify-center">
                <svg className="w-8 h-8 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
              </div>
              <p className="text-gray-500 mb-4">加载失败: {error}</p>
              <button 
                onClick={refresh}
                className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 transition-colors"
              >
                重试
              </button>
            </div>
          ) : filteredWebsites.length === 0 ? (
            <div className="text-center py-12">
              <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-gray-100 flex items-center justify-center">
                <svg className="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
                </svg>
              </div>
              <p className="text-gray-500 mb-4">
                {searchTerm ? '没有找到匹配的网站' : '还没有添加任何监控网站'}
              </p>
              {!searchTerm && (
                <button 
                  onClick={handleAdd}
                  className="px-4 py-2 bg-emerald-500 text-white rounded-lg hover:bg-emerald-600 transition-colors"
                >
                  添加第一个网站
                </button>
              )}
            </div>
          ) : (
            <div className="space-y-6">
              {Object.keys(groupedWebsites).map(groupId => (
                <div key={groupId}>
                  {selectedGroup === 'all' && (
                    <h2 className="text-sm font-medium text-gray-600 mb-3 flex items-center">
                      <span className="w-2 h-2 rounded-full bg-emerald-500 mr-2"></span>
                      {getGroupName(groupId)}
                      <span className="ml-2 text-gray-400">({groupedWebsites[groupId].length})</span>
                    </h2>
                  )}
                  <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 sm:gap-4">
                    {groupedWebsites[groupId].map(website => (
                      <WebsiteCard
                        key={website.website?.id}
                        website={website}
                        onRefresh={handleRefresh}
                        onEdit={handleEdit}
                        onDelete={handleDelete}
                      />
                    ))}
                  </div>
                </div>
              ))}
            </div>
          )}
        </section>
      </main>

      {/* 底部信息 */}
      <footer className="py-6 text-center text-sm text-gray-500">
        <p>萌芽Ping © 2026 </p>
      </footer>

      {/* 添加/编辑弹窗 */}
      <WebsiteModal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        onSuccess={refresh}
        editData={editData}
      />
    </div>
  );
}
