import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { supabase } from '../lib/supabase';
import { useAuth } from '../contexts/AuthContext';
import { Trophy, Loader2, Check, Clock, X as XIcon } from 'lucide-react';

interface LeaderboardEntry {
  is_current_user: boolean;
  nombre: string;
  puntos: number;
}

interface DashboardData {
  user: {
    first_name: string;
    last_name: string;
    initials: string;
  };
  total_points: number;
  leaderboard: LeaderboardEntry[];
}

export default function Dashboard() {
  const { user, isLoading: authLoading } = useAuth();
  const navigate = useNavigate();
  
  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (authLoading) return;
    if (!user) {
      navigate('/auth');
      return;
    }

    const fetchDashboard = async () => {
      let isSuccess = false;
      try {
        const { data: dbData, error: dbError } = await supabase.rpc('rpc_get_dashboard', { p_user_id: user.id });
        if (dbError) throw dbError;
        
        const parsedData = Array.isArray(dbData) ? dbData[0] : dbData;
        
        if (parsedData && parsedData.user) {
          setData(parsedData);
          isSuccess = true;
          return;
        }
      } catch (err: any) {
        // Silently catch the error to fall back to visual demonstration
      } finally {
        // Fallback for visual demonstration as requested
        if (!isSuccess) {
          setData({
            user: { first_name: 'MARCELA', last_name: 'GIRALDO', initials: 'MG' },
            total_points: 340,
            leaderboard: [
              { is_current_user: false, nombre: 'CARLOS P.', puntos: 500 },
              { is_current_user: true, nombre: 'MARCELA G.', puntos: 340 },
              { is_current_user: false, nombre: 'JUAN M.', puntos: 200 }
            ]
          });
        }
        setLoading(false);
      }
    };

    fetchDashboard();
  }, [user, navigate]);

  if (loading) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center w-full relative min-h-[500px]">
        <div className="absolute inset-0 bg-brand-dark-blue flex items-center justify-center z-50">
          <Loader2 className="animate-spin text-brand-yellow w-12 h-12" />
        </div>
      </div>
    );
  }

  if (!data) return null;

  const initial = data.user.initials || 'US';
  const fullName = `${data.user.first_name} ${data.user.last_name}`;
  
  const userRankIndex = data.leaderboard.findIndex(entry => entry.is_current_user);
  const position = userRankIndex !== -1 ? userRankIndex + 1 : '-';

  return (
    <div className="flex-1 relative w-full overflow-hidden bg-brand-dark-blue flex flex-col">
      {/* Image Background */}
      <div className="absolute inset-0 z-0 overflow-hidden pointer-events-none">
        <img 
          src={`${import.meta.env.BASE_URL}images/bg-perfil.png`}
          alt="Background"
          className="w-full h-full object-cover object-center"
        />
      </div>

      <div className="relative z-10 w-full max-w-6xl mx-auto px-4 py-8 flex flex-col items-start min-h-screen">
        
        {/* Header Profile */}
        <div className="flex items-center gap-4 mb-8">
          <div className="w-16 h-16 rounded-full bg-brand-blue text-brand-yellow font-display text-2xl flex items-center justify-center flex-shrink-0 border-4 border-brand-yellow shadow-lg italic">
            {initial}
          </div>
          <h1 className="font-display italic text-4xl text-white drop-shadow-md uppercase tracking-wide">
            {fullName}
          </h1>
        </div>

        <div className="flex flex-col lg:flex-row gap-6 w-full">
          {/* Left Column (Stats) */}
          <div className="flex flex-col gap-6 w-full lg:w-[45%] xl:w-[40%]">
            
            {/* Puntos Card */}
            <div className="bg-brand-dark-blue/95 border border-brand-yellow/50 rounded-[2rem] p-8 shadow-2xl relative overflow-hidden text-brand-dark-blue">
               {/* Star decorations */}
               <div className="absolute top-4 right-8 text-brand-yellow">
                  <svg width="40" height="40" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z"/></svg>
               </div>
               <div className="absolute top-12 right-24 text-brand-yellow scale-50 opacity-80">
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z"/></svg>
               </div>
               <div className="absolute top-20 right-6 text-brand-yellow scale-75 opacity-90">
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L15.09 8.26L22 9.27L17 14.14L18.18 21.02L12 17.77L5.82 21.02L7 14.14L2 9.27L8.91 8.26L12 2Z"/></svg>
               </div>

               <h2 className="font-display text-brand-yellow text-xl uppercase tracking-wider mb-1">Puntos Acumulados</h2>
               <div className="font-display text-white text-6xl md:text-7xl mb-2 flex items-baseline gap-2">
                 {data.total_points} <span className="text-3xl text-white font-normal lowercase tracking-wide">puntos</span>
               </div>
            </div>

            {/* Posicion Card */}
            <div className="bg-brand-cream rounded-[2rem] p-6 shadow-xl flex items-center justify-center gap-6 text-brand-dark-blue">
               <Trophy className="text-brand-blue w-16 h-16 shrink-0" strokeWidth={1.5} />
               <div className="flex flex-col">
                 <h3 className="font-display text-2xl uppercase tracking-wide text-brand-blue">Posición en ranking:</h3>
                 <p className="font-display italic text-6xl text-brand-red leading-none mt-1">#{position}</p>
               </div>
            </div>

          </div>

          {/* Right Column (History & Actions) */}
          <div className="w-full lg:w-[55%] xl:w-[60%] flex flex-col gap-6 text-brand-dark-blue">
            
            <div className="bg-brand-cream rounded-[2rem] p-6 sm:p-8 shadow-2xl flex-1 flex flex-col relative">
               <h3 className="font-display text-3xl uppercase text-brand-blue mb-6">Ranking de Puntos</h3>
               
               <div className="flex flex-col border border-gray-200 rounded-xl overflow-y-auto overflow-x-hidden bg-white/50 flex-1 max-h-[400px] [&::-webkit-scrollbar]:w-2 [&::-webkit-scrollbar-track]:bg-gray-200 [&::-webkit-scrollbar-track]:rounded-full [&::-webkit-scrollbar-thumb]:bg-brand-blue [&::-webkit-scrollbar-thumb]:rounded-full">
                 {data.leaderboard.slice(0, 10).map((item, idx) => {
                   const isAprobada = true; // Use check icon for everyone
                   
                   let rowBg = item.is_current_user ? 'bg-brand-yellow/20' : (idx % 2 === 0 ? 'bg-transparent' : 'bg-gray-50');

                   return (
                     <div key={idx} className={`flex items-center justify-between p-4 border-b border-gray-100 last:border-0 ${rowBg}`}>
                       <div className="flex items-center gap-2 w-1/3">
                         <span className="font-display text-brand-red text-xl ml-2 mr-2">#{idx + 1}</span>
                         <span className={`font-bold text-brand-navy`}>
                           {item.nombre}
                         </span>
                       </div>
                       
                       <div className="text-brand-navy font-bold w-1/3 text-right">
                         {item.puntos} Pts
                       </div>
                     </div>
                   );
                 })}
               </div>
            </div>

            <button 
              onClick={() => navigate('/upload')}
              className="w-full bg-brand-yellow text-brand-navy font-bold text-xl py-5 rounded-full hover:bg-brand-yellow/90 active:scale-[0.98] transition-all shadow-lg shadow-brand-yellow/20"
            >
              Subir nueva factura
            </button>

          </div>
        </div>

      </div>
    </div>
  );
}
