"use client";

import { useState, useEffect } from 'react';
import { DeviceAnalytics } from '../../api/types';

export default function DeviceAnalyticsPage() {
  const [deviceData, setDeviceData] = useState<DeviceAnalytics | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [dateRange, setDateRange] = useState({
    from: new Date('2024-02-01'),
    to: new Date('2025-03-05')
  });

  useEffect(() => {
    const fetchDeviceData = async () => {
      try {
        setIsLoading(true);
        setError(null);

        const response = await fetch(`/api/events/devices?startTime=${dateRange.from.toISOString().split('T')[0]}T00:00:00Z&endTime=${dateRange.to.toISOString().split('T')[0]}T23:59:59Z`);
        if (!response.ok) throw new Error('Failed to fetch device data');
        
        const data = await response.json();
        setDeviceData(data.data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'An error occurred');
      } finally {
        setIsLoading(false);
      }
    };

    fetchDeviceData();
  }, [dateRange]);

  return (
    <div className="container mx-auto px-4 py-8">
      {/* 页面标题 */}
      <div className="mb-8">
        <h1 className="text-2xl font-bold text-foreground">Device Analytics</h1>
        <p className="mt-2 text-text-secondary">Analyze visitor distribution by devices, browsers, and operating systems</p>
      </div>

      {/* 时间范围选择器 */}
      <div className="bg-card-bg rounded-xl p-6 mb-8">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-1">Start Date</label>
            <input
              type="date"
              className="block w-full px-3 py-2 bg-background border border-card-border rounded-md text-sm"
              value={dateRange.from.toISOString().split('T')[0]}
              onChange={e => setDateRange(prev => ({ ...prev, from: new Date(e.target.value) }))}
            />
          </div>
          <div>
            <label className="block text-sm font-medium text-text-secondary mb-1">End Date</label>
            <input
              type="date"
              className="block w-full px-3 py-2 bg-background border border-card-border rounded-md text-sm"
              value={dateRange.to.toISOString().split('T')[0]}
              onChange={e => setDateRange(prev => ({ ...prev, to: new Date(e.target.value) }))}
            />
          </div>
        </div>
      </div>

      {/* 设备类型分析 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
        {/* 设备类型 */}
        <div className="bg-card-bg rounded-xl p-6">
          <h3 className="text-lg font-medium text-foreground mb-4">Device Types</h3>
          {deviceData?.deviceTypes.map(item => (
            <div key={item.type} className="mb-4 last:mb-0">
              <div className="flex justify-between items-center mb-1">
                <span className="text-sm text-foreground">{item.type}</span>
                <span className="text-sm text-text-secondary">{item.count} ({item.percentage.toFixed(1)}%)</span>
              </div>
              <div className="w-full bg-background rounded-full h-2">
                <div
                  className="bg-accent-blue h-2 rounded-full"
                  style={{ width: `${item.percentage}%` }}
                />
              </div>
            </div>
          ))}
        </div>

        {/* 浏览器 */}
        <div className="bg-card-bg rounded-xl p-6">
          <h3 className="text-lg font-medium text-foreground mb-4">Browsers</h3>
          {deviceData?.browsers.map(item => (
            <div key={item.name} className="mb-4 last:mb-0">
              <div className="flex justify-between items-center mb-1">
                <span className="text-sm text-foreground">{item.name}</span>
                <span className="text-sm text-text-secondary">{item.count} ({item.percentage.toFixed(1)}%)</span>
              </div>
              <div className="w-full bg-background rounded-full h-2">
                <div
                  className="bg-accent-green h-2 rounded-full"
                  style={{ width: `${item.percentage}%` }}
                />
              </div>
            </div>
          ))}
        </div>

        {/* 操作系统 */}
        <div className="bg-card-bg rounded-xl p-6">
          <h3 className="text-lg font-medium text-foreground mb-4">Operating Systems</h3>
          {deviceData?.operatingSystems.map(item => (
            <div key={item.name} className="mb-4 last:mb-0">
              <div className="flex justify-between items-center mb-1">
                <span className="text-sm text-foreground">{item.name}</span>
                <span className="text-sm text-text-secondary">{item.count} ({item.percentage.toFixed(1)}%)</span>
              </div>
              <div className="w-full bg-background rounded-full h-2">
                <div
                  className="bg-accent-red h-2 rounded-full"
                  style={{ width: `${item.percentage}%` }}
                />
              </div>
            </div>
          ))}
        </div>
      </div>

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

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

      {/* 无数据状态 */}
      {!isLoading && !error && !deviceData && (
        <div className="flex justify-center items-center p-8 text-text-secondary">
          <p>No device data available</p>
        </div>
      )}
    </div>
  );
} 