import { useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '@/features/auth/store/authStore';
import { useUser } from '@/features/auth/hooks/useUser';
// Action 2.1.1.4: Removed unused library imports - library data now comes from dashboard endpoint
import { useDashboard } from '@/features/dashboard/hooks/useDashboard';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import {
  Music,
  MessageSquare,
  Users,
  Heart,
  Library,
  Upload,
  Plus,
  TrendingUp,
  Activity,
  Clock,
} from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { fr } from 'date-fns/locale';
import { KodoEmptyState } from '@/components/ui/KodoEmptyState';
import { cn } from '@/lib/utils';

/**
 * Dashboard Premium - Version MVP avec UI moderne et professionnelle
 * Intégration complète avec backend Go uniquement
 */
export function DashboardPage() {
  // Action 2.1.1.4: Removed fetchItems call - library preview now comes from dashboard endpoint
  const {
    stats,
    recentActivity,
    isLoading: isLoadingDashboard,
  } = useDashboard();
  const navigate = useNavigate();
  const { data: user } = useUser();

  const formatNumber = (num: number): string => {
    if (num >= 1000000) {
      return `${(num / 1000000).toFixed(1)}M`;
    }
    if (num >= 1000) {
      return `${(num / 1000).toFixed(1)}K`;
    }
    return num.toString();
  };

  const dashboardStats = [
    {
      title: 'Pistes écoutées',
      value: stats ? formatNumber(stats.tracks_played) : '0',
      change: stats?.tracks_played_change || '+0%',
      icon: Music,
      color: 'text-kodo-cyan',
      bgGradient: 'from-kodo-cyan/10 to-kodo-cyan/5',
    },
    {
      title: 'Messages envoyés',
      value: stats ? formatNumber(stats.messages_sent) : '0',
      change: stats?.messages_sent_change || '+0%',
      icon: MessageSquare,
      color: 'text-kodo-lime',
      bgGradient: 'from-kodo-lime/10 to-kodo-lime/5',
    },
    {
      title: 'Favoris',
      value: stats ? formatNumber(stats.favorites) : '0',
      change: stats?.favorites_change || '+0%',
      icon: Heart,
      color: 'text-kodo-magenta',
      bgGradient: 'from-kodo-magenta/10 to-kodo-magenta/5',
    },
    {
      title: 'Amis actifs',
      value: stats ? formatNumber(stats.active_friends) : '0',
      change: stats?.active_friends_change || '+0%',
      icon: Users,
      color: 'text-kodo-gold',
      bgGradient: 'from-kodo-gold/10 to-kodo-gold/5',
    },
  ];

  const formattedTimestamps = useMemo(() => {
    const cache: Record<string, string> = {};
    return recentActivity.reduce(
      (acc, activity) => {
        if (!cache[activity.timestamp]) {
          try {
            cache[activity.timestamp] = formatDistanceToNow(
              new Date(activity.timestamp),
              {
                addSuffix: true,
                locale: fr,
              },
            );
          } catch {
            cache[activity.timestamp] = 'Récemment';
          }
        }
        acc[activity.timestamp] = cache[activity.timestamp];
        return acc;
      },
      {} as Record<string, string>,
    );
  }, [recentActivity]);

  const formatTimestamp = (timestamp: string) => {
    return formattedTimestamps[timestamp] || 'Récemment';
  };

  return (
    <div className="space-y-8 pb-12 animate-fade-in">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-6">
        <div className="space-y-2">
          <h1 className="text-4xl font-bold text-white tracking-tight">
            Bienvenue,{' '}
            <span className="text-kodo-cyan">
              {user?.username || 'Utilisateur'}
            </span>
          </h1>
          <p className="text-kodo-secondary text-sm">
            Voici un aperçu de votre activité sur Veza
          </p>
        </div>

        <div className="flex items-center gap-3">
          <Button
            variant="outline"
            size="lg"
            onClick={() => navigate('/library')}
            className="hidden sm:flex"
          >
            <Library className="w-4 h-4 mr-2" />
            Bibliothèque
          </Button>
          <Button
            variant="default"
            size="lg"
            onClick={() => navigate('/library?action=upload')}
            className="shadow-glow-cyan"
          >
            <Plus className="w-4 h-4 mr-2" />
            Upload Track
          </Button>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {dashboardStats.map((stat, i) => (
          <Card
            key={i}
            className="group hover:border-kodo-cyan/30 transition-all duration-300"
          >
            <CardContent className="p-6">
              <div className="flex items-center justify-between mb-4">
                <div
                  className={cn(
                    'p-3 rounded-xl bg-gradient-to-br',
                    stat.bgGradient,
                    'border border-white/10 group-hover:scale-110 transition-transform duration-300',
                  )}
                >
                  <stat.icon className={cn('w-5 h-5', stat.color)} />
                </div>
                <div
                  className={cn(
                    'text-xs font-semibold px-2 py-1 rounded-lg',
                    stat.change.startsWith('+')
                      ? 'bg-kodo-lime/10 text-kodo-lime border border-kodo-lime/20'
                      : 'bg-kodo-red/10 text-kodo-red border border-kodo-red/20',
                  )}
                >
                  {stat.change}
                </div>
              </div>
              <div className="space-y-1">
                <p className="text-xs font-medium text-kodo-secondary uppercase tracking-wider">
                  {stat.title}
                </p>
                <p className="text-3xl font-bold text-white">{stat.value}</p>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Activity Feed */}
        <div className="lg:col-span-2 space-y-6">
          {/* Chart Card */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="flex items-center gap-2">
                  <TrendingUp className="w-5 h-5 text-kodo-cyan" />
                  Activité récente
                </CardTitle>
                <div className="flex items-center gap-2">
                  <button className="text-xs font-medium text-kodo-secondary hover:text-kodo-cyan transition-colors px-2 py-1">
                    7J
                  </button>
                  <button className="text-xs font-medium text-kodo-cyan bg-kodo-cyan/10 px-2 py-1 rounded-lg border border-kodo-cyan/20">
                    30J
                  </button>
                  <button className="text-xs font-medium text-kodo-secondary hover:text-kodo-cyan transition-colors px-2 py-1">
                    MAX
                  </button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="h-64 flex items-end gap-2">
                {[40, 65, 35, 90, 55, 75, 45, 85, 60, 70, 50, 95].map(
                  (h, i) => (
                    <div
                      key={i}
                      className="flex-1 bg-gradient-to-t from-kodo-cyan/40 to-kodo-cyan/20 rounded-t-lg transition-all duration-300 hover:from-kodo-cyan/60 hover:to-kodo-cyan/40 cursor-pointer group relative"
                      style={{ height: `${h}%` }}
                    >
                      <div className="absolute -top-8 left-1/2 -translate-x-1/2 bg-kodo-ink border border-kodo-cyan/30 text-kodo-cyan text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity whitespace-nowrap shadow-lg">
                        {h}%
                      </div>
                    </div>
                  ),
                )}
              </div>
            </CardContent>
          </Card>

          {/* Recent Activity List */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Activity className="w-5 h-5 text-kodo-cyan" />
                Dernières activités
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {isLoadingDashboard ? (
                  Array(3)
                    .fill(0)
                    .map((_, i) => (
                      <div
                        key={i}
                        className="h-16 bg-white/5 rounded-xl animate-pulse"
                      />
                    ))
                ) : recentActivity.length > 0 ? (
                  recentActivity.slice(0, 5).map((act, i) => (
                    <div
                      key={i}
                      className="flex items-center justify-between p-4 rounded-xl bg-white/5 border border-white/5 hover:bg-white/10 hover:border-kodo-cyan/30 transition-all duration-200 group cursor-pointer"
                    >
                      <div className="flex items-center gap-4">
                        <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-kodo-cyan/20 to-kodo-cyan/10 border border-kodo-cyan/20 flex items-center justify-center group-hover:scale-110 transition-transform">
                          <Clock className="w-5 h-5 text-kodo-cyan" />
                        </div>
                        <div>
                          <p className="text-sm font-semibold text-white group-hover:text-kodo-cyan transition-colors">
                            {act.title}
                          </p>
                          <p className="text-xs text-kodo-secondary mt-0.5">
                            {act.description || 'Activité système'}
                          </p>
                        </div>
                      </div>
                      <div className="text-xs text-kodo-secondary font-mono">
                        {formatTimestamp(act.timestamp)}
                      </div>
                    </div>
                  ))
                ) : (
                  <KodoEmptyState
                    icon={Activity}
                    title="Aucune activité récente"
                    description="Vos activités apparaîtront ici"
                  />
                )}
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Quick Actions */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Actions rapides</CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              {[
                {
                  label: 'Upload Track',
                  icon: Upload,
                  action: () => navigate('/library?action=upload'),
                  variant: 'default' as const,
                },
                {
                  label: 'Bibliothèque',
                  icon: Library,
                  action: () => navigate('/library'),
                  variant: 'outline' as const,
                },
                {
                  label: 'Messages',
                  icon: MessageSquare,
                  action: () => navigate('/chat'),
                  variant: 'outline' as const,
                },
              ].map((action, i) => (
                <Button
                  key={i}
                  variant={action.variant}
                  className="w-full justify-start"
                  onClick={action.action}
                >
                  <action.icon className="w-4 h-4 mr-2" />
                  {action.label}
                </Button>
              ))}
            </CardContent>
          </Card>

          {/* System Status */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg">Statut système</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-kodo-secondary">Backend API</span>
                  <span className="text-kodo-lime font-semibold flex items-center gap-1">
                    <div className="w-2 h-2 rounded-full bg-kodo-lime animate-pulse" />
                    En ligne
                  </span>
                </div>
                <div className="h-1.5 w-full bg-white/5 rounded-full overflow-hidden">
                  <div className="h-full bg-kodo-lime w-full" />
                </div>
              </div>
              <div className="pt-4 border-t border-white/5">
                <Button
                  variant="ghost"
                  className="w-full"
                  onClick={() => navigate('/settings')}
                >
                  Paramètres système
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
