"use client";

import { useState, useEffect } from 'react';
import { format } from 'date-fns';
import { DateRangePicker } from '@/app/components/ui/DateRangePicker';
import TimeSeriesChart from '@/app/components/charts/TimeSeriesChart';
import GeoAnalytics from '@/app/components/analytics/GeoAnalytics';
import DevicePieCharts from '@/app/components/charts/DevicePieCharts';
import { EventsSummary, TimeSeriesData, GeoData, DeviceAnalytics as DeviceAnalyticsType } from '@/app/api/types';

// 事件类型定义
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 DashboardPage() {
  const [dateRange, setDateRange] = useState({
    from: new Date('2024-02-01'),
    to: new Date('2025-03-05')
  });

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [summary, setSummary] = useState<EventsSummary | null>(null);
  const [timeSeriesData, setTimeSeriesData] = useState<TimeSeriesData[]>([]);
  const [geoData, setGeoData] = useState<GeoData[]>([]);
  const [deviceData, setDeviceData] = useState<DeviceAnalyticsType | null>(null);
  const [events, setEvents] = useState<Event[]>([]);
  const [urlFilter, setUrlFilter] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      setError(null);

      try {
        const startTime = format(dateRange.from, "yyyy-MM-dd'T'HH:mm:ss'Z'");
        const endTime = format(dateRange.to, "yyyy-MM-dd'T'HH:mm:ss'Z'");

        // 并行获取所有数据
        const [summaryRes, timeSeriesRes, geoRes, deviceRes, eventsRes] = await Promise.all([
          fetch(`/api/events/summary?startTime=${startTime}&endTime=${endTime}`),
          fetch(`/api/events/time-series?startTime=${startTime}&endTime=${endTime}`),
          fetch(`/api/events/geo?startTime=${startTime}&endTime=${endTime}`),
          fetch(`/api/events/devices?startTime=${startTime}&endTime=${endTime}`),
          fetchEvents(startTime, endTime, urlFilter || undefined)
        ]);

        const [summaryData, timeSeriesData, geoData, deviceData] = await Promise.all([
          summaryRes.json(),
          timeSeriesRes.json(),
          geoRes.json(),
          deviceRes.json()
        ]);

        if (!summaryRes.ok) throw new Error(summaryData.error || 'Failed to fetch summary data');
        if (!timeSeriesRes.ok) throw new Error(timeSeriesData.error || 'Failed to fetch time series data');
        if (!geoRes.ok) throw new Error(geoData.error || 'Failed to fetch geo data');
        if (!deviceRes.ok) throw new Error(deviceData.error || 'Failed to fetch device data');

        setSummary(summaryData.data);
        setTimeSeriesData(timeSeriesData.data);
        setGeoData(geoData.data);
        setDeviceData(deviceData.data);
        setEvents(eventsRes || []);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred while fetching data');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [dateRange, urlFilter]);

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-red-500">{error}</div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-2xl font-bold text-gray-900">Analytics Dashboard</h1>
        <DateRangePicker
          value={dateRange}
          onChange={setDateRange}
        />
      </div>

      {summary && (
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          <div className="bg-white rounded-lg shadow p-6">
            <h3 className="text-sm font-medium text-gray-500">Total Events</h3>
            <p className="text-2xl font-semibold text-gray-900">
              {typeof summary.totalEvents === 'number' ? summary.totalEvents.toLocaleString() : summary.totalEvents}
            </p>
          </div>
          <div className="bg-white rounded-lg shadow p-6">
            <h3 className="text-sm font-medium text-gray-500">Unique Visitors</h3>
            <p className="text-2xl font-semibold text-gray-900">
              {typeof summary.uniqueVisitors === 'number' ? summary.uniqueVisitors.toLocaleString() : summary.uniqueVisitors}
            </p>
          </div>
          <div className="bg-white rounded-lg shadow p-6">
            <h3 className="text-sm font-medium text-gray-500">Total Conversions</h3>
            <p className="text-2xl font-semibold text-gray-900">
              {typeof summary.totalConversions === 'number' ? summary.totalConversions.toLocaleString() : summary.totalConversions}
            </p>
          </div>
          <div className="bg-white rounded-lg shadow p-6">
            <h3 className="text-sm font-medium text-gray-500">Avg. Time Spent</h3>
            <p className="text-2xl font-semibold text-gray-900">
              {summary.averageTimeSpent?.toFixed(1) || '0'}s
            </p>
          </div>
        </div>
      )}

      <div className="bg-white rounded-lg shadow p-6 mb-8">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Event Trends</h2>
        <div className="h-96">
          <TimeSeriesChart data={timeSeriesData} />
        </div>
      </div>

      <div className="mb-8">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Device Analytics</h2>
        {deviceData && <DevicePieCharts data={deviceData} />}
      </div>

      <div className="bg-white rounded-lg shadow p-6 mb-8">
        <h2 className="text-lg font-semibold text-gray-900 mb-4">Geographic Distribution</h2>
        <GeoAnalytics data={geoData} />
      </div>

      {/* 事件列表部分 */}
      <div className="bg-white rounded-lg shadow overflow-hidden mb-8">
        <div className="p-6 border-b border-gray-200">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">Recent Events</h2>
          
          <div className="flex items-center space-x-4 mb-4">
            <div className="flex-1">
              <label className="block text-sm font-medium text-gray-500 mb-1">
                Filter by URL ID
              </label>
              <input
                type="text"
                value={urlFilter}
                onChange={e => setUrlFilter(e.target.value)}
                className="w-full px-3 py-2 bg-white border border-gray-300 rounded-md text-sm text-gray-900"
                placeholder="Enter URL ID to filter"
              />
            </div>
          </div>
        </div>
        
        <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 && events.length === 0 && (
          <div className="flex justify-center items-center p-8 text-gray-500">
            No events found
          </div>
        )}
      </div>
    </div>
  );
} 