'use client';

import { useState, useEffect } from 'react';
import { AlertCircle, Receipt, CheckCircle, FileWarning, RefreshCw, BarChart2 } from 'lucide-react';
import { apiFetch } from '@/lib/csrf/client';

interface ReceiptStats {
  totalReceipts: number;
  mathValidRate: number;
  needsReview: number;
  categories: { label: string; count: number; color: string }[];
  topScanners: { rank: number; email: string; name: string | null; count: number }[];
  dailyScans: { date: string; count: number }[];
}

export default function AdminReceiptsPage() {
  const [stats, setStats] = useState<ReceiptStats | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchStats = async () => {
    try {
      setIsLoading(true);
      setError(null);
      const res = await apiFetch('/api/admin/receipts');
      if (!res.ok) throw new Error('Failed to fetch receipt analytics');
      const data = await res.json();
      setStats(data);
    } catch (err: any) {
      setError(err.message || 'An error occurred');
    } finally {
      setIsLoading(false);
    }
  };

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

  if (isLoading) {
    return (
      <div className="space-y-6 animate-pulse">
        <div className="h-8 w-48 bg-slate-200 rounded"></div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {[...Array(3)].map((_, i) => (
            <div key={i} className="h-32 bg-white rounded-2xl border border-slate-200"></div>
          ))}
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mt-6">
          <div className="h-80 bg-white rounded-2xl border border-slate-200"></div>
          <div className="h-80 bg-white rounded-2xl border border-slate-200"></div>
        </div>
      </div>
    );
  }

  if (error || !stats) {
    return (
      <div className="p-6 bg-red-50 border border-red-200 rounded-2xl flex items-center justify-between text-red-700">
        <div className="flex items-center gap-3">
          <AlertCircle size={22} className="text-red-600" />
          <div>
            <h3 className="font-semibold text-red-900">Fehler beim Laden der Beleg-Statistiken</h3>
            <p className="text-xs text-red-600 mt-0.5">{error}</p>
          </div>
        </div>
        <button onClick={fetchStats} className="px-4 py-2 bg-red-600 text-white rounded-xl text-xs font-semibold hover:bg-red-700 transition-all shadow-xs">
          <RefreshCw size={14} className="inline mr-1.5" /> Erneut versuchen
        </button>
      </div>
    );
  }

  const formatNumber = (num: number) => num.toLocaleString('de-DE');
  const validRateOk = stats.mathValidRate >= 95;
  const maxCategoryCount = Math.max(...stats.categories.map(c => c.count), 1);
  const maxDailyCount = Math.max(...stats.dailyScans.map(d => d.count), 1);

  return (
    <div className="space-y-6 max-w-7xl mx-auto">
      <div className="flex items-center justify-between pb-2 border-b border-slate-200">
        <div>
          <h1 className="text-2xl sm:text-3xl font-bold tracking-tight text-slate-900 font-sans">
            Beleg- & OCR-Analyse
          </h1>
          <p className="text-xs sm:text-sm text-slate-500 mt-1">
            Qualitätsmetriken, Erkennungsraten und Kategorien.
          </p>
        </div>
        <button onClick={fetchStats} className="p-2 text-slate-600 hover:text-slate-900 bg-white border border-slate-200 rounded-xl transition-colors shadow-xs">
          <RefreshCw size={16} className={isLoading ? "animate-spin" : ""} />
        </button>
      </div>

      {/* Stats Row */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 sm:gap-6">
        <div className="bg-white border border-slate-200 rounded-2xl p-6 flex flex-col justify-between shadow-xs">
          <div className="flex items-center justify-between mb-2">
            <span className="text-xs font-semibold text-slate-500 uppercase font-mono">Erfasste Belege</span>
            <div className="p-2 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-600">
              <Receipt size={18} />
            </div>
          </div>
          <div className="text-3xl font-mono font-bold text-slate-900">{formatNumber(stats.totalReceipts)}</div>
          <p className="text-xs text-slate-400 mt-2">In der Datenbank gespeichert</p>
        </div>
        
        <div className="bg-white border border-slate-200 rounded-2xl p-6 flex flex-col justify-between shadow-xs">
          <div className="flex items-center justify-between mb-2">
            <span className="text-xs font-semibold text-slate-500 uppercase font-mono">Mathematische Validität</span>
            <div className={`p-2 rounded-xl ${validRateOk ? 'bg-emerald-50 border border-emerald-200 text-emerald-600' : 'bg-amber-50 border border-amber-200 text-amber-600'}`}>
              <CheckCircle size={18} />
            </div>
          </div>
          <div className={`text-3xl font-mono font-bold ${validRateOk ? "text-emerald-700" : "text-amber-700"}`}>
            {stats.mathValidRate.toFixed(1)}%
          </div>
          <p className="text-xs text-slate-400 mt-2">Belege mit exaktem Abgleich Netto + MwSt = Brutto</p>
        </div>

        <div className="bg-white border border-slate-200 rounded-2xl p-6 flex flex-col justify-between shadow-xs">
          <div className="flex items-center justify-between mb-2">
            <span className="text-xs font-semibold text-slate-500 uppercase font-mono">Prüfbedarf (Review)</span>
            <div className="p-2 rounded-xl bg-amber-50 border border-amber-200 text-amber-600">
              <FileWarning size={18} />
            </div>
          </div>
          <div className="text-3xl font-mono font-bold text-slate-900">{formatNumber(stats.needsReview)}</div>
          <p className="text-xs text-slate-400 mt-2">Niedriger Konfidenzwert oder manuelle Nacharbeit nötig</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Category Distribution */}
        <div className="bg-white border border-slate-200 rounded-2xl p-6 shadow-xs">
          <h3 className="text-sm font-bold text-slate-900 mb-6 flex items-center gap-2">
            <BarChart2 size={16} className="text-sky-600" />
            Kategorienverteilung
          </h3>
          <div className="space-y-4">
            {stats.categories.map((cat, i) => {
              const widthPercent = (cat.count / maxCategoryCount) * 100;
              return (
                <div key={i} className="flex items-center gap-4">
                  <div className="w-28 text-xs font-semibold text-slate-700 truncate" title={cat.label}>
                    {cat.label}
                  </div>
                  <div className="flex-1 h-3 bg-slate-100 rounded-full overflow-hidden border border-slate-200">
                    <div 
                      className="h-full rounded-full transition-all duration-300" 
                      style={{ width: `${Math.max(4, widthPercent)}%`, backgroundColor: cat.color || '#0284C7' }} 
                    />
                  </div>
                  <div className="w-12 text-right text-xs font-mono font-bold text-slate-800">
                    {formatNumber(cat.count)}
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Top Scanners */}
        <div className="bg-white border border-slate-200 rounded-2xl p-6 flex flex-col shadow-xs">
          <h3 className="text-sm font-bold text-slate-900 mb-4">Top Scanner Accounts</h3>
          <div className="flex-1 overflow-auto -mx-6 px-6">
            <table className="w-full text-xs sm:text-sm text-left">
              <thead className="text-[11px] font-mono text-slate-500 uppercase sticky top-0 bg-slate-50 border-b border-slate-200">
                <tr>
                  <th className="py-2.5 px-3 w-12 text-center">Rang</th>
                  <th className="py-2.5 px-3">Benutzer</th>
                  <th className="py-2.5 px-3 text-right">Scans</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {stats.topScanners.map((user, i) => (
                  <tr key={i} className="hover:bg-slate-50 transition-colors">
                    <td className="py-3 px-3 text-center">
                      <span className={`inline-flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold
                        ${user.rank === 1 ? 'bg-amber-100 text-amber-800 border border-amber-300' : 
                          user.rank === 2 ? 'bg-slate-200 text-slate-700 border border-slate-300' : 
                          user.rank === 3 ? 'bg-amber-50 text-amber-900 border border-amber-200' : 
                          'bg-slate-100 text-slate-600'}`}
                      >
                        {user.rank}
                      </span>
                    </td>
                    <td className="py-3 px-3">
                      <div className="font-semibold text-slate-900 truncate max-w-[200px]">{user.email}</div>
                      {user.name && <div className="text-xs text-slate-400 truncate max-w-[200px]">{user.name}</div>}
                    </td>
                    <td className="py-3 px-3 text-right font-mono text-emerald-700 font-bold">
                      {formatNumber(user.count)}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}
