'use client';

import { useState, useEffect } from 'react';
import { useTranslation } from '@/hooks/useTranslation';
import {
  MessageSquare,
  Ticket,
  ThumbsUp,
  Clock,
  TrendingUp,
  AlertTriangle,
  Loader2,
} from 'lucide-react';
import { aiAssistantApi, type DashboardData } from '@/lib/api/ai-assistant';

/**
 * AI 助手管理仪表盘
 */
export default function AIAssistantDashboardPage() {
  const { t } = useTranslation();
  const [dashboard, setDashboard] = useState<DashboardData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadDashboard();
  }, []);

  const loadDashboard = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const response: any = await aiAssistantApi.getDashboard();
      setDashboard(response.data);
    } catch (err) {
      console.error('Failed to load dashboard:', err);
      setError('Failed to load dashboard data');
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-gray-400" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <AlertTriangle className="w-12 h-12 text-red-400 mx-auto mb-4" />
          <p className="text-gray-600">{error}</p>
          <button
            onClick={loadDashboard}
            className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
          >
            Retry
          </button>
        </div>
      </div>
    );
  }

  const stats = [
    {
      label: 'Calls (24h)',
      value: dashboard?.callsLast24h || 0,
      icon: MessageSquare,
      color: 'bg-blue-500',
    },
    {
      label: 'Calls (7d)',
      value: dashboard?.callsLast7d || 0,
      icon: TrendingUp,
      color: 'bg-green-500',
    },
    {
      label: 'Success Rate',
      value: `${((dashboard?.successRate || 0) * 100).toFixed(1)}%`,
      icon: ThumbsUp,
      color: 'bg-purple-500',
    },
    {
      label: 'Avg Response Time',
      value: `${(dashboard?.avgResponseTime || 0).toFixed(2)}${'s'}`,
      icon: Clock,
      color: 'bg-orange-500',
    },
    {
      label: 'Satisfaction Rate',
      value: `${((dashboard?.satisfactionRate || 0) * 100).toFixed(1)}%`,
      icon: ThumbsUp,
      color: 'bg-pink-500',
    },
    {
      label: 'Pending Tickets',
      value: dashboard?.pendingTickets || 0,
      icon: Ticket,
      color: 'bg-yellow-500',
    },
    {
      label: 'Hallucination Reports',
      value: dashboard?.hallucinations || 0,
      icon: AlertTriangle,
      color: 'bg-red-500',
    },
  ];

  return (
    <div className="p-6">
      {/* 页面标题 */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold text-gray-900">
          {'AI Assistant Dashboard'}
        </h1>
        <p className="text-gray-500 mt-1">
          {'Monitor AI assistant performance and usage'}
        </p>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        {stats.map((stat, index) => {
          const Icon = stat.icon;
          return (
            <div
              key={index}
              className="bg-white rounded-xl p-5 shadow-sm border border-gray-100"
            >
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-500">{stat.label}</p>
                  <p className="text-2xl font-bold text-gray-900 mt-1">{stat.value}</p>
                </div>
                <div className={`${stat.color} p-3 rounded-lg`}>
                  <Icon className="w-5 h-5 text-white" />
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* 场景分布 */}
      {dashboard?.categoryDistribution && Object.keys(dashboard.categoryDistribution).length > 0 && (
        <div className="bg-white rounded-xl p-6 shadow-sm border border-gray-100">
          <h2 className="text-lg font-semibold text-gray-900 mb-4">
            {'Category Distribution'}
          </h2>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
            {Object.entries(dashboard.categoryDistribution).map(([category, count]) => {
              const total = Object.values(dashboard.categoryDistribution).reduce((a, b) => a + b, 0);
              const percentage = total > 0 ? ((count / total) * 100).toFixed(1) : 0;
              return (
                <div key={category} className="text-center p-4 bg-gray-50 rounded-lg">
                  <p className="text-sm text-gray-500">
                    {t.aiAssistant?.categories?.[category as keyof typeof t.aiAssistant.categories] || category}
                  </p>
                  <p className="text-xl font-bold text-gray-900 mt-1">{count}</p>
                  <p className="text-xs text-gray-400 mt-0.5">{percentage}%</p>
                </div>
              );
            })}
          </div>
        </div>
      )}
    </div>
  );
}
