"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 DeviceAnalytics from '@/app/components/analytics/DeviceAnalytics';
import { EventsSummary, TimeSeriesData, GeoData, DeviceAnalytics as DeviceAnalyticsType } from '@/app/api/types';

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);

  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] = 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}`)
        ]);

        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);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred while fetching data');
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [dateRange]);

  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 && <DeviceAnalytics data={deviceData} />}
      </div>

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