"use client";

import { useState, useEffect } from 'react';
import { format } from 'date-fns';

// 更复杂的事件类型定义
interface Event {
  event_id?: string;
  url_id: string;
  url: string;
  event_type: string;
  visitor_id: string;
  created_at: string;
  referrer?: string;
  browser?: string;
  os?: string;
  device_type?: string;
  country?: string;
  city?: string;
}

// 创建获取事件的函数
const fetchEvents = async (
  startTime?: string, 
  endTime?: string, 
  urlId?: string, 
  eventType?: string
): Promise<Event[]> => {
  try {
    // 构建查询参数
    const params = new URLSearchParams();
    if (startTime) params.append('startTime', startTime);
    if (endTime) params.append('endTime', endTime);
    if (urlId) params.append('urlId', urlId);
    if (eventType) params.append('eventType', eventType);
    
    // 发送请求
    const response = await fetch(`/api/events?${params.toString()}`);
    
    if (!response.ok) {
      throw new Error('Failed to fetch events');
    }
    
    const data = await response.json();
    return data.data || [];
  } catch (error) {
    console.error('Error fetching events:', error);
    return [];
  }
};

const formatDate = (dateString: string) => {
  if (!dateString) return '';
  try {
    return format(new Date(dateString), 'yyyy-MM-dd HH:mm:ss');
  } catch {
    return dateString;
  }
};

export default function EventsPage() {
  // 状态定义
  const [events, setEvents] = useState<Event[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [filters, setFilters] = useState({
    startDate: format(new Date(Date.now() - 7 * 24 * 60 * 60 * 1000), 'yyyy-MM-dd'),
    endDate: format(new Date(), 'yyyy-MM-dd'),
    urlId: '',
    eventType: ''
  });
  
  // 加载事件数据
  useEffect(() => {
    const loadEvents = async () => {
      setLoading(true);
      setError(null);
      
      try {
        const startTime = `${filters.startDate}T00:00:00Z`;
        const endTime = `${filters.endDate}T23:59:59Z`;
        
        const eventsData = await fetchEvents(
          startTime,
          endTime,
          filters.urlId || undefined,
          filters.eventType || undefined
        );
        
        setEvents(eventsData);
      } catch (err) {
        setError('Failed to load events');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };
    
    loadEvents();
  }, [filters]);
  
  // 处理筛选条件变化
  const handleFilterChange = (name: string, value: string) => {
    setFilters(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  return (
    <div className="container mx-auto px-4 py-8">
      {/* 页面标题 */}
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-gray-900">Events</h1>
        <p className="mt-2 text-gray-600">View and analyze all events for your URLs</p>
      </div>
      
      {/* 过滤器面板 */}
      <div className="bg-white rounded-lg shadow p-6 mb-8">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-500 mb-1">
              Start Date
            </label>
            <input
              type="date"
              value={filters.startDate}
              onChange={e => handleFilterChange('startDate', e.target.value)}
              className="block w-full px-3 py-2 bg-white border border-gray-300 rounded-md text-sm text-gray-900"
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-500 mb-1">
              End Date
            </label>
            <input
              type="date"
              value={filters.endDate}
              onChange={e => handleFilterChange('endDate', e.target.value)}
              className="block w-full px-3 py-2 bg-white border border-gray-300 rounded-md text-sm text-gray-900"
            />
          </div>
          
          <div>
            <label className="block text-sm font-medium text-gray-500 mb-1">
              URL ID
            </label>
            <input
              type="text"
              value={filters.urlId}
              onChange={e => handleFilterChange('urlId', e.target.value)}
              className="block w-full px-3 py-2 bg-white border border-gray-300 rounded-md text-sm text-gray-900"
              placeholder="Filter by URL ID"
            />
          </div>
        </div>
      </div>
      
      {/* 事件表格 */}
      <div className="bg-white rounded-lg shadow overflow-hidden">
        <div className="overflow-x-auto">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Time
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  URL ID
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  URL
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Event Type
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Visitor ID
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Referrer
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Location
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {events.map((event, index) => (
                <tr key={event.event_id || index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {formatDate(event.created_at)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {event.url_id}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    <a href={event.url} className="text-blue-600 hover:underline" target="_blank" rel="noopener noreferrer">
                      {event.url}
                    </a>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm">
                    <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
                      event.event_type === 'click' 
                        ? 'bg-green-100 text-green-800' 
                        : 'bg-blue-100 text-blue-800'
                    }`}>
                      {event.event_type}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {event.visitor_id.substring(0, 8)}...
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {event.referrer || '-'}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                    {event.country && event.city ? `${event.city}, ${event.country}` : (event.country || '-')}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* 加载状态 */}
        {loading && (
          <div className="flex justify-center items-center p-8">
            <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
          </div>
        )}

        {/* 错误状态 */}
        {error && (
          <div className="flex justify-center items-center p-8 text-red-500">
            {error}
          </div>
        )}

        {/* 空状态 */}
        {!loading && !error && events.length === 0 && (
          <div className="flex justify-center items-center p-8 text-gray-500">
            No events found
          </div>
        )}
      </div>
    </div>
  );
}
