import React from 'react';
import { Plus, BookOpen, Clock, TrendingUp, Award } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { supabase } from '../../lib/supabase';
import type { Story, Student } from '../../types/database';

interface DashboardMetrics {
  totalStories: number;
  averageReadingFluency: number;
  totalReadingTime: number;
  currentLevel: number;
}

export function StudentDashboardPage() {
  const navigate = useNavigate();
  const [student, setStudent] = React.useState<Student | null>(null);
  const [stories, setStories] = React.useState<Story[]>([]);
  const [metrics, setMetrics] = React.useState<DashboardMetrics>({
    totalStories: 0,
    averageReadingFluency: 0,
    totalReadingTime: 0,
    currentLevel: 1
  });
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);

  React.useEffect(() => {
    const fetchDashboardData = async () => {
      try {
        const { data: { session } } = await supabase.auth.getSession();
        if (!session?.user?.id) return;

        // Buscar dados do aluno
        const { data: studentData, error: studentError } = await supabase
          .from('students')
          .select(`
            *,
            class:classes(name, grade),
            school:schools(name)
          `)
          .eq('id', session.user.id)
          .single();

        if (studentError) throw studentError;
        setStudent(studentData);

        // Buscar histórias do aluno
        const { data: storiesData, error: storiesError } = await supabase
          .from('stories')
          .select('*')
          .eq('student_id', session.user.id)
          .order('created_at', { ascending: false })
          .limit(6);

        if (storiesError) throw storiesError;
        setStories(storiesData || []);

        // Calcular métricas
        // Em produção: Implementar cálculos reais baseados nos dados
        setMetrics({
          totalStories: storiesData?.length || 0,
          averageReadingFluency: 85, // Exemplo
          totalReadingTime: 120, // Exemplo: 120 minutos
          currentLevel: 3 // Exemplo
        });

      } catch (err) {
        console.error('Erro ao carregar dashboard:', err);
        setError('Não foi possível carregar seus dados');
      } finally {
        setLoading(false);
      }
    };

    fetchDashboardData();
  }, []);

  if (loading) {
    return (
      <div className="animate-pulse">
        <div className="h-32 bg-gray-200 rounded-xl mb-8" />
        <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
          {[...Array(4)].map((_, i) => (
            <div key={i} className="h-24 bg-gray-200 rounded-xl" />
          ))}
        </div>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {[...Array(6)].map((_, i) => (
            <div key={i} className="h-64 bg-gray-200 rounded-xl" />
          ))}
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-12">
        <div className="text-red-500 mb-4">{error}</div>
        <button
          onClick={() => window.location.reload()}
          className="text-purple-600 hover:text-purple-700"
        >
          Tentar novamente
        </button>
      </div>
    );
  }

  return (
    <div>
      {/* Cabeçalho */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-8">
        <div className="flex justify-between items-start">
          <div className="flex items-center gap-4">
            <div className="w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center">
              {student?.avatar_url ? (
                <img
                  src={student.avatar_url}
                  alt={student?.name}
                  className="w-full h-full rounded-full object-cover"
                />
              ) : (
                <span className="text-2xl font-bold text-purple-600">
                  {student?.name?.charAt(0)}
                </span>
              )}
            </div>
            <div>
              <h1 className="text-2xl font-bold text-gray-900">{student?.name}</h1>
              <p className="text-gray-500">
                {(student?.class as any)?.grade} • {(student?.class as any)?.name} • {(student?.school as any)?.name}
              </p>
            </div>
          </div>
          <button
            onClick={() => navigate('/aluno/historias/nova')}
            className="flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition"
          >
            <Plus className="h-5 w-5" />
            Nova História
          </button>
        </div>
      </div>

      {/* Métricas */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center gap-4">
            <div className="p-3 bg-purple-100 rounded-lg">
              <BookOpen className="h-6 w-6 text-purple-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">Total de Histórias</p>
              <p className="text-2xl font-bold text-gray-900">{metrics.totalStories}</p>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center gap-4">
            <div className="p-3 bg-green-100 rounded-lg">
              <TrendingUp className="h-6 w-6 text-green-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">Fluência Média</p>
              <p className="text-2xl font-bold text-gray-900">{metrics.averageReadingFluency}%</p>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center gap-4">
            <div className="p-3 bg-blue-100 rounded-lg">
              <Clock className="h-6 w-6 text-blue-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">Tempo de Leitura</p>
              <p className="text-2xl font-bold text-gray-900">{metrics.totalReadingTime}min</p>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
          <div className="flex items-center gap-4">
            <div className="p-3 bg-yellow-100 rounded-lg">
              <Award className="h-6 w-6 text-yellow-600" />
            </div>
            <div>
              <p className="text-sm text-gray-500">Nível Atual</p>
              <p className="text-2xl font-bold text-gray-900">{metrics.currentLevel}</p>
            </div>
          </div>
        </div>
      </div>

      {/* Histórias Recentes */}
      <div>
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-bold text-gray-900">Histórias Recentes</h2>
          <button
            onClick={() => navigate('/aluno/historias')}
            className="text-purple-600 hover:text-purple-700"
          >
            Ver todas
          </button>
        </div>

        {stories.length === 0 ? (
          <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-12 text-center">
            <BookOpen className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              Nenhuma história ainda
            </h3>
            <p className="text-gray-500 mb-6">
              Comece sua jornada criando sua primeira história!
            </p>
            <button
              onClick={() => navigate('/aluno/historias/nova')}
              className="inline-flex items-center gap-2 px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition"
            >
              <Plus className="h-5 w-5" />
              Criar História
            </button>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
            {stories.map((story) => (
              <div
                key={story.id}
                className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden cursor-pointer hover:shadow-md transition"
                onClick={() => navigate(`/aluno/historias/${story.id}`)}
              >
                {story.content.pages[0].image && (
                  <img
                    src={story.content.pages[0].image}
                    alt={story.title}
                    className="w-full h-48 object-cover"
                  />
                )}
                <div className="p-6">
                  <h3 className="font-medium text-gray-900 mb-2">{story.title}</h3>
                  <div className="flex items-center justify-between text-sm text-gray-500">
                    <span>{new Date(story.created_at).toLocaleDateString()}</span>
                    <span className={`px-2 py-1 rounded-full text-xs font-medium ${
                      story.status === 'published'
                        ? 'bg-green-100 text-green-800'
                        : 'bg-yellow-100 text-yellow-800'
                    }`}>
                      {story.status === 'published' ? 'Publicada' : 'Rascunho'}
                    </span>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
} 