/**
 * Payment Analytics Dashboard
 * Real-time dashboard for collection performance
 */

import React, { useState, useEffect } from 'react';

interface CollectionStats {
  period: string;
  totalDue: number;
  totalCollected: number;
  collectionRate: number;
  totalCalls: number;
  successfulCalls: number;
  callSuccessRate: number;
  pendingCallbacks: number;
  completedCallbacks: number;
}

interface AgentPerformance {
  agentId: string;
  agentName: string;
  totalCalls: number;
  successRate: number;
  totalCollected: number;
}

interface TrendData {
  date: string;
  collected: number;
  due: number;
  calls: number;
}

interface ActivityItem {
  id: string;
  type: string;
  description: string;
  amount?: number;
  timestamp: string;
  status: string;
}

export function PaymentAnalyticsDashboard() {
  const [period, setPeriod] = useState<string>('month');
  const [loading, setLoading] = useState(true);
  const [stats, setStats] = useState<CollectionStats | null>(null);
  const [agents, setAgents] = useState<AgentPerformance[]>([]);
  const [trends, setTrends] = useState<TrendData[]>([]);
  const [activity, setActivity] = useState<ActivityItem[]>([]);

  useEffect(() => {
    fetchDashboardData();
  }, [period]);

  const fetchDashboardData = async () => {
    setLoading(true);
    try {
      const response = await fetch(`/api/plugins/database-connector/analytics/dashboard?period=${period}`);
      const data = await response.json();
      setStats(data.stats);
      setAgents(data.agentPerformance || []);
      setTrends(data.trends || []);
      setActivity(data.recentActivity || []);
    } catch (error) {
      console.error('Failed to fetch dashboard data:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatCurrency = (amount: number) => {
    return amount.toLocaleString('ar-SA') + ' ريال';
  };

  const formatPercentage = (value: number) => {
    return value.toFixed(1) + '%';
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'success': return 'text-green-600';
      case 'failed': return 'text-red-600';
      case 'pending': return 'text-yellow-600';
      default: return 'text-gray-600';
    }
  };

  const getActivityIcon = (type: string) => {
    switch (type) {
      case 'payment': return '💰';
      case 'call': return '📞';
      case 'promise': return '🤝';
      case 'callback': return '🔄';
      default: return '📋';
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  return (
    <div className="p-6" dir="rtl">
      {/* Header */}
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-2xl font-bold">📊 لوحة تحليلات التحصيل</h1>
          <p className="text-muted-foreground">تتبع أداء التحصيل والمكالمات</p>
        </div>
        <div className="flex gap-2">
          {['today', 'week', 'month', 'year'].map((p) => (
            <button
              key={p}
              onClick={() => setPeriod(p)}
              className={`px-4 py-2 rounded-lg ${
                period === p 
                  ? 'bg-primary text-primary-foreground' 
                  : 'bg-muted hover:bg-muted/80'
              }`}
            >
              {p === 'today' ? 'اليوم' : p === 'week' ? 'الأسبوع' : p === 'month' ? 'الشهر' : 'السنة'}
            </button>
          ))}
        </div>
      </div>

      {/* Main Stats Cards */}
      {stats && (
        <div className="grid grid-cols-4 gap-4 mb-6">
          {/* Total Due */}
          <div className="bg-card border rounded-lg p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-muted-foreground">إجمالي المستحقات</p>
                <p className="text-2xl font-bold">{formatCurrency(stats.totalDue)}</p>
              </div>
              <div className="text-3xl">💳</div>
            </div>
          </div>

          {/* Total Collected */}
          <div className="bg-green-50 border border-green-200 rounded-lg p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-green-600">تم التحصيل</p>
                <p className="text-2xl font-bold text-green-700">{formatCurrency(stats.totalCollected)}</p>
                <p className="text-sm text-green-600">{formatPercentage(stats.collectionRate)} نسبة التحصيل</p>
              </div>
              <div className="text-3xl">✅</div>
            </div>
          </div>

          {/* Call Success Rate */}
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-blue-600">نجاح المكالمات</p>
                <p className="text-2xl font-bold text-blue-700">{formatPercentage(stats.callSuccessRate)}</p>
                <p className="text-sm text-blue-600">{stats.successfulCalls} / {stats.totalCalls} مكالمة</p>
              </div>
              <div className="text-3xl">📞</div>
            </div>
          </div>

          {/* Pending Callbacks */}
          <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-yellow-600">مكالمات معلقة</p>
                <p className="text-2xl font-bold text-yellow-700">{stats.pendingCallbacks}</p>
                <p className="text-sm text-yellow-600">{stats.completedCallbacks} مكتملة</p>
              </div>
              <div className="text-3xl">⏰</div>
            </div>
          </div>
        </div>
      )}

      <div className="grid grid-cols-3 gap-6">
        {/* Collection Progress */}
        <div className="col-span-2 bg-card border rounded-lg p-4">
          <h3 className="font-semibold mb-4">📈 تقدم التحصيل</h3>
          
          {stats && (
            <div className="mb-4">
              <div className="flex justify-between text-sm mb-1">
                <span>التقدم</span>
                <span>{formatPercentage(stats.collectionRate)}</span>
              </div>
              <div className="h-4 bg-muted rounded-full overflow-hidden">
                <div 
                  className="h-full bg-green-500 rounded-full transition-all duration-500"
                  style={{ width: `${stats.collectionRate}%` }}
                />
              </div>
              <div className="flex justify-between text-xs text-muted-foreground mt-1">
                <span>{formatCurrency(stats.totalCollected)}</span>
                <span>{formatCurrency(stats.totalDue)}</span>
              </div>
            </div>
          )}

          {/* Simple Trend Chart (using divs) */}
          <div className="h-40 flex items-end gap-1 mt-4">
            {trends.slice(-14).map((trend, i) => (
              <div key={i} className="flex-1 flex flex-col items-center">
                <div 
                  className="w-full bg-green-400 rounded-t"
                  style={{ height: `${(trend.collected / 10000) * 100}%`, minHeight: '4px' }}
                />
                <div 
                  className="w-full bg-gray-200 rounded-b"
                  style={{ height: `${((trend.due - trend.collected) / 10000) * 100}%`, minHeight: '4px' }}
                />
                <span className="text-xs text-muted-foreground mt-1 rotate-45 origin-left">
                  {trend.date.split('-')[2]}
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* Recent Activity */}
        <div className="bg-card border rounded-lg p-4">
          <h3 className="font-semibold mb-4">🔔 النشاط الأخير</h3>
          <div className="space-y-3 max-h-64 overflow-y-auto">
            {activity.map((item) => (
              <div key={item.id} className="flex items-start gap-3 p-2 bg-muted/50 rounded">
                <span className="text-xl">{getActivityIcon(item.type)}</span>
                <div className="flex-1">
                  <p className="text-sm">{item.description}</p>
                  {item.amount && (
                    <p className="text-sm font-semibold">{formatCurrency(item.amount)}</p>
                  )}
                  <p className="text-xs text-muted-foreground">
                    {new Date(item.timestamp).toLocaleString('ar-SA')}
                  </p>
                </div>
                <span className={`text-xs ${getStatusColor(item.status)}`}>
                  {item.status === 'success' ? '✓' : item.status === 'pending' ? '⏳' : '✗'}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Agent Performance */}
      <div className="mt-6 bg-card border rounded-lg p-4">
        <h3 className="font-semibold mb-4">👥 أداء الوكلاء</h3>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="border-b">
                <th className="text-right py-2 px-4">الوكيل</th>
                <th className="text-right py-2 px-4">المكالمات</th>
                <th className="text-right py-2 px-4">نسبة النجاح</th>
                <th className="text-right py-2 px-4">المحصّل</th>
                <th className="text-right py-2 px-4">الأداء</th>
              </tr>
            </thead>
            <tbody>
              {agents.map((agent) => (
                <tr key={agent.agentId} className="border-b hover:bg-muted/50">
                  <td className="py-3 px-4 font-medium">{agent.agentName}</td>
                  <td className="py-3 px-4">{agent.totalCalls}</td>
                  <td className="py-3 px-4">
                    <span className={agent.successRate >= 70 ? 'text-green-600' : 'text-yellow-600'}>
                      {formatPercentage(agent.successRate)}
                    </span>
                  </td>
                  <td className="py-3 px-4">{formatCurrency(agent.totalCollected)}</td>
                  <td className="py-3 px-4">
                    <div className="h-2 w-20 bg-muted rounded-full overflow-hidden">
                      <div 
                        className={`h-full rounded-full ${agent.successRate >= 70 ? 'bg-green-500' : 'bg-yellow-500'}`}
                        style={{ width: `${agent.successRate}%` }}
                      />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Quick Actions */}
      <div className="mt-6 grid grid-cols-4 gap-4">
        <button className="bg-primary text-primary-foreground p-4 rounded-lg flex items-center gap-3 hover:opacity-90">
          <span className="text-2xl">📞</span>
          <div className="text-right">
            <p className="font-semibold">بدء حملة اتصال</p>
            <p className="text-sm opacity-80">اتصال تلقائي بالعملاء</p>
          </div>
        </button>
        
        <button className="bg-card border p-4 rounded-lg flex items-center gap-3 hover:bg-muted">
          <span className="text-2xl">📊</span>
          <div className="text-right">
            <p className="font-semibold">تصدير تقرير</p>
            <p className="text-sm text-muted-foreground">PDF أو Excel</p>
          </div>
        </button>
        
        <button className="bg-card border p-4 rounded-lg flex items-center gap-3 hover:bg-muted">
          <span className="text-2xl">⚙️</span>
          <div className="text-right">
            <p className="font-semibold">إعدادات التحصيل</p>
            <p className="text-sm text-muted-foreground">قوالب وقواعد</p>
          </div>
        </button>
        
        <button className="bg-card border p-4 rounded-lg flex items-center gap-3 hover:bg-muted">
          <span className="text-2xl">📋</span>
          <div className="text-right">
            <p className="font-semibold">قائمة العملاء</p>
            <p className="text-sm text-muted-foreground">عرض المتأخرين</p>
          </div>
        </button>
      </div>
    </div>
  );
}

export default PaymentAnalyticsDashboard;
