"use client";

import { useEffect, useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useTranslationStore } from "@/lib/store";
import { motion } from "framer-motion";
import { Users, Activity, Settings, FileText, TrendingUp, Server, Key, LogOut, RefreshCw, Search, ChevronRight, Shield, Zap, Globe, DollarSign } from "lucide-react";

interface DashboardData {
  translations_today: number;
  translations_total: number;
  active_users: number;
  popular_languages: { [key: string]: number };
  average_processing_time: number;
  cache_hit_rate: number;
  openrouter_usage?: {
    total_cost: number;
    requests_count: number;
    models_used: { [key: string]: number };
  };
}

interface User {
  id: string;
  email: string;
  username: string;
  plan: string;
  translations_count: number;
  is_active: boolean;
  created_at: string;
  last_login?: string;
}

interface AdminSettings {
  default_provider: string;
  openrouter_enabled: boolean;
  google_enabled: boolean;
  max_file_size_mb: number;
  rate_limit_per_minute: number;
  cache_enabled: boolean;
}

function AdminContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { adminToken } = useTranslationStore();
  
  const [activeTab, setActiveTab] = useState<"overview" | "users" | "config" | "settings">("overview");
  const [dashboardData, setDashboardData] = useState<DashboardData | null>(null);
  const [users, setUsers] = useState<User[]>([]);
  const [settings, setSettings] = useState<AdminSettings>({
    default_provider: "google",
    openrouter_enabled: true,
    google_enabled: true,
    max_file_size_mb: 10,
    rate_limit_per_minute: 60,
    cache_enabled: true
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [refreshing, setRefreshing] = useState(false);

  const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:8000";

  useEffect(() => {
    const tab = searchParams.get("tab");
    if (tab && ["overview", "users", "config", "settings"].includes(tab)) {
      setActiveTab(tab as any);
    }
  }, [searchParams]);

  useEffect(() => {
    if (!adminToken) {
      router.push("/admin/login");
      return;
    }
    fetchDashboardData();
  }, [adminToken]);

  useEffect(() => {
    if (activeTab === "users" && users.length === 0) {
      fetchUsers();
    }
  }, [activeTab]);

  const fetchDashboardData = async () => {
    try {
      setLoading(true);
      const response = await fetch(`${API_BASE}/admin/dashboard`, {
        headers: { Authorization: `Bearer ${adminToken}` }
      });
      if (!response.ok) throw new Error("Failed to fetch dashboard data");
      const data = await response.json();
      setDashboardData(data);
    } catch (err) {
      setError("Erreur de chargement des données");
      console.error(err);
    } finally {
      setLoading(false);
    }
  };

  const fetchUsers = async () => {
    try {
      const response = await fetch(`${API_BASE}/admin/users`, {
        headers: { Authorization: `Bearer ${adminToken}` }
      });
      if (!response.ok) throw new Error("Failed to fetch users");
      const data = await response.json();
      setUsers(data.users || []);
    } catch (err) {
      console.error("Error fetching users:", err);
    }
  };

  const refreshData = async () => {
    setRefreshing(true);
    await fetchDashboardData();
    if (activeTab === "users") {
      await fetchUsers();
    }
    setRefreshing(false);
  };

  const handleLogout = () => {
    useTranslationStore.getState().setAdminToken(null);
    router.push("/admin/login");
  };

  const filteredUsers = users.filter(user => 
    user.email?.toLowerCase().includes(searchQuery.toLowerCase()) ||
    user.username?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  if (loading) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center">
        <div className="text-white text-xl flex items-center gap-3">
          <RefreshCw className="animate-spin" />
          Chargement...
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900">
      {/* Header */}
      <header className="bg-black/30 backdrop-blur-xl border-b border-white/10">
        <div className="max-w-7xl mx-auto px-6 py-4 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Shield className="w-8 h-8 text-purple-400" />
            <h1 className="text-2xl font-bold text-white">Administration</h1>
          </div>
          <div className="flex items-center gap-4">
            <button
              onClick={refreshData}
              disabled={refreshing}
              className="p-2 rounded-lg bg-white/10 hover:bg-white/20 text-white transition-all"
            >
              <RefreshCw className={`w-5 h-5 ${refreshing ? 'animate-spin' : ''}`} />
            </button>
            <button
              onClick={handleLogout}
              className="flex items-center gap-2 px-4 py-2 rounded-lg bg-red-500/20 hover:bg-red-500/30 text-red-400 transition-all"
            >
              <LogOut className="w-4 h-4" />
              Déconnexion
            </button>
          </div>
        </div>
      </header>

      <div className="max-w-7xl mx-auto px-6 py-8">
        {/* Tab Navigation */}
        <div className="flex gap-2 mb-8 bg-black/20 p-2 rounded-xl w-fit">
          {[
            { id: "overview", label: "Vue d'ensemble", icon: Activity },
            { id: "users", label: "Utilisateurs", icon: Users },
            { id: "config", label: "Configuration", icon: Server },
            { id: "settings", label: "Paramètres", icon: Settings }
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => setActiveTab(tab.id as any)}
              className={`flex items-center gap-2 px-4 py-2 rounded-lg transition-all ${
                activeTab === tab.id
                  ? "bg-purple-600 text-white shadow-lg"
                  : "text-gray-400 hover:text-white hover:bg-white/10"
              }`}
            >
              <tab.icon className="w-4 h-4" />
              {tab.label}
            </button>
          ))}
        </div>

        {/* Overview Tab */}
        {activeTab === "overview" && dashboardData && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="space-y-6"
          >
            {/* Stats Grid */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <StatCard
                title="Traductions Aujourd'hui"
                value={dashboardData.translations_today ?? 0}
                icon={FileText}
                color="purple"
              />
              <StatCard
                title="Total Traductions"
                value={dashboardData.translations_total ?? 0}
                icon={TrendingUp}
                color="blue"
              />
              <StatCard
                title="Utilisateurs Actifs"
                value={dashboardData.active_users ?? 0}
                icon={Users}
                color="green"
              />
              <StatCard
                title="Taux Cache"
                value={`${((dashboardData.cache_hit_rate ?? 0) * 100).toFixed(1)}%`}
                icon={Zap}
                color="yellow"
              />
            </div>

            {/* OpenRouter Usage */}
            {dashboardData.openrouter_usage && (
              <div className="bg-black/20 backdrop-blur-xl rounded-2xl border border-white/10 p-6">
                <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                  <Globe className="w-5 h-5 text-purple-400" />
                  Utilisation OpenRouter
                </h3>
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="bg-white/5 rounded-xl p-4">
                    <p className="text-gray-400 text-sm">Coût Total</p>
                    <p className="text-2xl font-bold text-green-400">
                      ${dashboardData.openrouter_usage.total_cost?.toFixed(4) ?? '0.0000'}
                    </p>
                  </div>
                  <div className="bg-white/5 rounded-xl p-4">
                    <p className="text-gray-400 text-sm">Requêtes</p>
                    <p className="text-2xl font-bold text-blue-400">
                      {dashboardData.openrouter_usage.requests_count ?? 0}
                    </p>
                  </div>
                  <div className="bg-white/5 rounded-xl p-4">
                    <p className="text-gray-400 text-sm">Temps Moyen</p>
                    <p className="text-2xl font-bold text-yellow-400">
                      {(dashboardData.average_processing_time ?? 0).toFixed(2)}s
                    </p>
                  </div>
                </div>
              </div>
            )}

            {/* Popular Languages */}
            <div className="bg-black/20 backdrop-blur-xl rounded-2xl border border-white/10 p-6">
              <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
                <Globe className="w-5 h-5 text-purple-400" />
                Langues Populaires
              </h3>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                {Object.entries(dashboardData.popular_languages || {}).slice(0, 8).map(([lang, count]) => (
                  <div key={lang} className="bg-white/5 rounded-xl p-4 text-center">
                    <p className="text-2xl font-bold text-white">{count}</p>
                    <p className="text-gray-400 text-sm uppercase">{lang}</p>
                  </div>
                ))}
              </div>
            </div>
          </motion.div>
        )}

        {/* Users Tab */}
        {activeTab === "users" && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="space-y-6"
          >
            {/* Search */}
            <div className="flex items-center gap-4">
              <div className="relative flex-1 max-w-md">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-gray-400" />
                <input
                  type="text"
                  placeholder="Rechercher un utilisateur..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-3 bg-black/30 border border-white/10 rounded-xl text-white placeholder:text-gray-500 focus:outline-none focus:border-purple-500"
                />
              </div>
              <div className="text-gray-400">
                {filteredUsers.length} utilisateur(s)
              </div>
            </div>

            {/* Users Table */}
            <div className="bg-black/20 backdrop-blur-xl rounded-2xl border border-white/10 overflow-hidden">
              <table className="w-full">
                <thead>
                  <tr className="border-b border-white/10">
                    <th className="text-left p-4 text-gray-400 font-medium">Utilisateur</th>
                    <th className="text-left p-4 text-gray-400 font-medium">Plan</th>
                    <th className="text-left p-4 text-gray-400 font-medium">Traductions</th>
                    <th className="text-left p-4 text-gray-400 font-medium">Statut</th>
                    <th className="text-left p-4 text-gray-400 font-medium">Inscrit le</th>
                    <th className="text-left p-4 text-gray-400 font-medium"></th>
                  </tr>
                </thead>
                <tbody>
                  {filteredUsers.map((user) => (
                    <tr key={user.id} className="border-b border-white/5 hover:bg-white/5 transition-colors">
                      <td className="p-4">
                        <div>
                          <p className="text-white font-medium">{user.username || 'N/A'}</p>
                          <p className="text-gray-400 text-sm">{user.email}</p>
                        </div>
                      </td>
                      <td className="p-4">
                        <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                          user.plan === 'premium' 
                            ? 'bg-purple-500/20 text-purple-400'
                            : user.plan === 'pro'
                            ? 'bg-blue-500/20 text-blue-400'
                            : 'bg-gray-500/20 text-gray-400'
                        }`}>
                          {user.plan || 'free'}
                        </span>
                      </td>
                      <td className="p-4 text-white">{user.translations_count ?? 0}</td>
                      <td className="p-4">
                        <span className={`px-3 py-1 rounded-full text-xs font-medium ${
                          user.is_active
                            ? 'bg-green-500/20 text-green-400'
                            : 'bg-red-500/20 text-red-400'
                        }`}>
                          {user.is_active ? 'Actif' : 'Inactif'}
                        </span>
                      </td>
                      <td className="p-4 text-gray-400 text-sm">
                        {user.created_at ? new Date(user.created_at).toLocaleDateString('fr-FR') : 'N/A'}
                      </td>
                      <td className="p-4">
                        <button className="p-2 rounded-lg hover:bg-white/10 text-gray-400 hover:text-white transition-all">
                          <ChevronRight className="w-5 h-5" />
                        </button>
                      </td>
                    </tr>
                  ))}
                  {filteredUsers.length === 0 && (
                    <tr>
                      <td colSpan={6} className="p-8 text-center text-gray-400">
                        Aucun utilisateur trouvé
                      </td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </motion.div>
        )}

        {/* Config Tab */}
        {activeTab === "config" && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="space-y-6"
          >
            {/* Translation Providers */}
            <div className="bg-black/20 backdrop-blur-xl rounded-2xl border border-white/10 p-6">
              <h3 className="text-lg font-semibold text-white mb-6 flex items-center gap-2">
                <Server className="w-5 h-5 text-purple-400" />
                Fournisseurs de Traduction
              </h3>
              
              <div className="space-y-4">
                {/* Google Translate */}
                <div className="flex items-center justify-between p-4 bg-white/5 rounded-xl">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 bg-blue-500/20 rounded-xl flex items-center justify-center">
                      <Globe className="w-6 h-6 text-blue-400" />
                    </div>
                    <div>
                      <h4 className="text-white font-medium">Google Translate</h4>
                      <p className="text-gray-400 text-sm">API officielle Google Cloud</p>
                    </div>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={settings.google_enabled}
                      onChange={(e) => setSettings({ ...settings, google_enabled: e.target.checked })}
                      className="sr-only peer"
                    />
                    <div className="w-11 h-6 bg-gray-700 peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                  </label>
                </div>

                {/* OpenRouter */}
                <div className="flex items-center justify-between p-4 bg-white/5 rounded-xl">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 bg-purple-500/20 rounded-xl flex items-center justify-center">
                      <Zap className="w-6 h-6 text-purple-400" />
                    </div>
                    <div>
                      <h4 className="text-white font-medium">OpenRouter</h4>
                      <p className="text-gray-400 text-sm">Modèles IA avancés (GPT-4, Claude, etc.)</p>
                    </div>
                  </div>
                  <label className="relative inline-flex items-center cursor-pointer">
                    <input
                      type="checkbox"
                      checked={settings.openrouter_enabled}
                      onChange={(e) => setSettings({ ...settings, openrouter_enabled: e.target.checked })}
                      className="sr-only peer"
                    />
                    <div className="w-11 h-6 bg-gray-700 peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                  </label>
                </div>
              </div>
            </div>

            {/* API Keys */}
            <div className="bg-black/20 backdrop-blur-xl rounded-2xl border border-white/10 p-6">
              <h3 className="text-lg font-semibold text-white mb-6 flex items-center gap-2">
                <Key className="w-5 h-5 text-purple-400" />
                Clés API
              </h3>
              
              <div className="space-y-4">
                <div className="p-4 bg-white/5 rounded-xl">
                  <label className="block text-gray-400 text-sm mb-2">Google Cloud API Key</label>
                  <div className="flex gap-2">
                    <input
                      type="password"
                      placeholder="••••••••••••••••"
                      className="flex-1 px-4 py-2 bg-black/30 border border-white/10 rounded-lg text-white placeholder:text-gray-500 focus:outline-none focus:border-purple-500"
                    />
                    <button className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-all">
                      Sauvegarder
                    </button>
                  </div>
                </div>

                <div className="p-4 bg-white/5 rounded-xl">
                  <label className="block text-gray-400 text-sm mb-2">OpenRouter API Key</label>
                  <div className="flex gap-2">
                    <input
                      type="password"
                      placeholder="••••••••••••••••"
                      className="flex-1 px-4 py-2 bg-black/30 border border-white/10 rounded-lg text-white placeholder:text-gray-500 focus:outline-none focus:border-purple-500"
                    />
                    <button className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-all">
                      Sauvegarder
                    </button>
                  </div>
                </div>
              </div>
            </div>

            {/* Default Provider */}
            <div className="bg-black/20 backdrop-blur-xl rounded-2xl border border-white/10 p-6">
              <h3 className="text-lg font-semibold text-white mb-6 flex items-center gap-2">
                <Settings className="w-5 h-5 text-purple-400" />
                Fournisseur par Défaut
              </h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <button
                  onClick={() => setSettings({ ...settings, default_provider: 'google' })}
                  className={`p-4 rounded-xl border-2 transition-all ${
                    settings.default_provider === 'google'
                      ? 'border-purple-500 bg-purple-500/10'
                      : 'border-white/10 bg-white/5 hover:border-white/20'
                  }`}
                >
                  <Globe className={`w-8 h-8 mb-2 ${settings.default_provider === 'google' ? 'text-purple-400' : 'text-gray-400'}`} />
                  <h4 className="text-white font-medium">Google Translate</h4>
                  <p className="text-gray-400 text-sm">Rapide et fiable</p>
                </button>

                <button
                  onClick={() => setSettings({ ...settings, default_provider: 'openrouter' })}
                  className={`p-4 rounded-xl border-2 transition-all ${
                    settings.default_provider === 'openrouter'
                      ? 'border-purple-500 bg-purple-500/10'
                      : 'border-white/10 bg-white/5 hover:border-white/20'
                  }`}
                >
                  <Zap className={`w-8 h-8 mb-2 ${settings.default_provider === 'openrouter' ? 'text-purple-400' : 'text-gray-400'}`} />
                  <h4 className="text-white font-medium">OpenRouter</h4>
                  <p className="text-gray-400 text-sm">IA avancée</p>
                </button>
              </div>
            </div>
          </motion.div>
        )}

        {/* Settings Tab */}
        {activeTab === "settings" && (
          <motion.div
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            className="space-y-6"
          >
            {/* Limits */}
            <div className="bg-black/20 backdrop-blur-xl rounded-2xl border border-white/10 p-6">
              <h3 className="text-lg font-semibold text-white mb-6 flex items-center gap-2">
                <Settings className="w-5 h-5 text-purple-400" />
                Limites
              </h3>
              
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-gray-400 text-sm mb-2">Taille max fichier (MB)</label>
                  <input
                    type="number"
                    value={settings.max_file_size_mb}
                    onChange={(e) => setSettings({ ...settings, max_file_size_mb: parseInt(e.target.value) || 10 })}
                    className="w-full px-4 py-3 bg-black/30 border border-white/10 rounded-xl text-white focus:outline-none focus:border-purple-500"
                  />
                </div>

                <div>
                  <label className="block text-gray-400 text-sm mb-2">Requêtes/minute</label>
                  <input
                    type="number"
                    value={settings.rate_limit_per_minute}
                    onChange={(e) => setSettings({ ...settings, rate_limit_per_minute: parseInt(e.target.value) || 60 })}
                    className="w-full px-4 py-3 bg-black/30 border border-white/10 rounded-xl text-white focus:outline-none focus:border-purple-500"
                  />
                </div>
              </div>
            </div>

            {/* Cache */}
            <div className="bg-black/20 backdrop-blur-xl rounded-2xl border border-white/10 p-6">
              <h3 className="text-lg font-semibold text-white mb-6 flex items-center gap-2">
                <Zap className="w-5 h-5 text-purple-400" />
                Cache
              </h3>
              
              <div className="flex items-center justify-between p-4 bg-white/5 rounded-xl">
                <div>
                  <h4 className="text-white font-medium">Cache des traductions</h4>
                  <p className="text-gray-400 text-sm">Améliore les performances et réduit les coûts</p>
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={settings.cache_enabled}
                    onChange={(e) => setSettings({ ...settings, cache_enabled: e.target.checked })}
                    className="sr-only peer"
                  />
                  <div className="w-11 h-6 bg-gray-700 peer-focus:ring-4 peer-focus:ring-purple-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-purple-600"></div>
                </label>
              </div>
            </div>

            {/* Save Button */}
            <div className="flex justify-end">
              <button className="px-6 py-3 bg-purple-600 hover:bg-purple-700 text-white rounded-xl font-medium transition-all flex items-center gap-2">
                Sauvegarder les paramètres
              </button>
            </div>
          </motion.div>
        )}
      </div>
    </div>
  );
}

function StatCard({ title, value, icon: Icon, color }: { title: string; value: string | number; icon: any; color: string }) {
  const colorClasses = {
    purple: 'bg-purple-500/20 text-purple-400',
    blue: 'bg-blue-500/20 text-blue-400',
    green: 'bg-green-500/20 text-green-400',
    yellow: 'bg-yellow-500/20 text-yellow-400'
  };

  return (
    <div className="bg-black/20 backdrop-blur-xl rounded-2xl border border-white/10 p-6">
      <div className="flex items-center justify-between mb-4">
        <div className={`p-3 rounded-xl ${colorClasses[color as keyof typeof colorClasses]}`}>
          <Icon className="w-6 h-6" />
        </div>
      </div>
      <p className="text-3xl font-bold text-white mb-1">{value}</p>
      <p className="text-gray-400 text-sm">{title}</p>
    </div>
  );
}

export default function AdminPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900 flex items-center justify-center">
        <div className="text-white text-xl">Chargement...</div>
      </div>
    }>
      <AdminContent />
    </Suspense>
  );
}
