import { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { supabase } from '@/lib/supabase';
import { Button } from '@/components/ui/button';
import { Plus, Search, Filter, PenTool } from 'lucide-react';
import { useSession } from '@/hooks/useSession';
import { useUppercasePreference } from '@/hooks/useUppercasePreference';
import { AdaptiveText } from '@/components/ui/adaptive-text';

interface Essay {
  id: string;
  title: string;
  type_id: string;
  genre_id: string;
  status: 'draft' | 'submitted' | 'analyzed';
  created_at: string;
  essay_type: {
    title: string;
  };
  essay_genre: {
    title: string;
  };
}

type EssayStatus = 'all' | 'draft' | 'submitted' | 'analyzed';
type SortOption = 'recent' | 'oldest' | 'title';

export function EssaysPage() {
  const navigate = useNavigate();
  const [essays, setEssays] = useState<Essay[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<EssayStatus>('all');
  const [sortBy, setSortBy] = useState<SortOption>('recent');
  const [showFilters, setShowFilters] = useState(false);
  const { session } = useSession();
  const { isUpperCase } = useUppercasePreference(session?.user?.id);

  useEffect(() => {
    loadEssays();
  }, [statusFilter, sortBy]);

  async function loadEssays() {
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session?.user?.id) return;

      const query = supabase
        .from('student_essays')
        .select(`
          *,
          essay_type:essay_types(title),
          essay_genre:essay_genres(title)
        `)
        .eq('student_id', session.user.id);

      if (statusFilter !== 'all') {
        query.eq('status', statusFilter);
      }

      const { data, error } = await query;
      if (error) {
        setError('Não foi possível carregar suas redações');
        return;
      }

      // Aplicar ordenação
      const sortedData = (data || []).sort((a, b) => {
        switch (sortBy) {
          case 'oldest':
            return new Date(a.created_at).getTime() - new Date(b.created_at).getTime();
          case 'title':
            return a.title.localeCompare(b.title);
          default: // recent
            return new Date(b.created_at).getTime() - new Date(a.created_at).getTime();
        }
      });

      setEssays(sortedData);
    } catch (error) {
      console.error('Erro ao carregar redações:', error);
      setError('Não foi possível carregar suas redações');
    } finally {
      setLoading(false);
    }
  }

  const filteredEssays = essays.filter(essay =>
    essay.title.toLowerCase().includes(searchTerm.toLowerCase())
  );

  function getStatusBadge(status: Essay['status']) {
    const statusMap = {
      draft: { label: 'Rascunho', variant: 'secondary' as const, classes: 'bg-yellow-100 text-yellow-800' },
      submitted: { label: 'Enviada', variant: 'default' as const, classes: 'bg-blue-100 text-blue-800' },
      analyzed: { label: 'Analisada', variant: 'success' as const, classes: 'bg-green-100 text-green-800' }
    };

    const { label, classes } = statusMap[status];
    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${classes}`}>
        <AdaptiveText text={label} isUpperCase={isUpperCase} />
      </span>
    );
  }

  if (loading) {
    return (
      <div className="animate-pulse">
        <div className="h-20 bg-gray-200 rounded-xl mb-6" />
        <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>
    );
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-2xl font-bold text-gray-900">
          <AdaptiveText text="Minhas Redações" isUpperCase={isUpperCase} />
        </h1>
        <Button 
          onClick={() => navigate('/aluno/redacoes/nova')}
          className="flex items-center gap-2"
          trackingId="essay-new-create-button"
          trackingProperties={{
            action: 'create_new_essay',
            page: 'essays_list'
          }}
        >
          <Plus className="h-5 w-5" />
          <AdaptiveText text="Nova Redação" isUpperCase={isUpperCase} />
        </Button>
      </div>

      <div className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden mb-6">
        <div className="p-4 border-b border-gray-200">
          <div className="flex flex-col md:flex-row gap-4">
            {/* Busca */}
            <div className="flex-1 relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-gray-400" />
              <input
                type="text"
                placeholder="Buscar redações..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-purple-500 focus:border-purple-500"
              />
            </div>

            {/* Filtros e Ordenação */}
            <div className="flex gap-2">
              <button
                onClick={() => setShowFilters(!showFilters)}
                className="flex items-center gap-2 px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50"
              >
                <Filter className="h-5 w-5" />
                <AdaptiveText text="Filtros" isUpperCase={isUpperCase} />
              </button>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as SortOption)}
                className="px-4 py-2 border border-gray-300 rounded-lg focus:ring-purple-500 focus:border-purple-500"
              >
                <option value="recent">Mais recentes</option>
                <option value="oldest">Mais antigas</option>
                <option value="title">Por título</option>
              </select>
            </div>
          </div>

          {/* Painel de Filtros */}
          {showFilters && (
            <div className="mt-4 pt-4 border-t border-gray-200">
              <div className="flex gap-2">
                <button
                  onClick={() => setStatusFilter('all')}
                  className={`px-4 py-2 rounded-lg ${
                    statusFilter === 'all'
                      ? 'bg-purple-100 text-purple-700'
                      : 'hover:bg-gray-100'
                  }`}
                >
                  <AdaptiveText text="Todas" isUpperCase={isUpperCase} />
                </button>
                <button
                  onClick={() => setStatusFilter('analyzed')}
                  className={`px-4 py-2 rounded-lg ${
                    statusFilter === 'analyzed'
                      ? 'bg-purple-100 text-purple-700'
                      : 'hover:bg-gray-100'
                  }`}
                >
                  <AdaptiveText text="Analisadas" isUpperCase={isUpperCase} />
                </button>
                <button
                  onClick={() => setStatusFilter('submitted')}
                  className={`px-4 py-2 rounded-lg ${
                    statusFilter === 'submitted'
                      ? 'bg-purple-100 text-purple-700'
                      : 'hover:bg-gray-100'
                  }`}
                >
                  <AdaptiveText text="Enviadas" isUpperCase={isUpperCase} />
                </button>
                <button
                  onClick={() => setStatusFilter('draft')}
                  className={`px-4 py-2 rounded-lg ${
                    statusFilter === 'draft'
                      ? 'bg-purple-100 text-purple-700'
                      : 'hover:bg-gray-100'
                  }`}
                >
                  <AdaptiveText text="Rascunhos" isUpperCase={isUpperCase} />
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Lista de Redações */}
        {filteredEssays.length === 0 ? (
          <div className="p-12 text-center">
            <PenTool className="h-12 w-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 mb-2">
              <AdaptiveText text="Nenhuma redação encontrada" isUpperCase={isUpperCase} />
            </h3>
            <p className="text-gray-500 mb-6">
              <AdaptiveText 
                text={searchTerm
                  ? 'Tente usar outros termos na busca'
                  : 'Comece criando sua primeira redação!'}
                isUpperCase={isUpperCase}
              />
            </p>
            {!searchTerm && (
              <Button
                onClick={() => navigate('/aluno/redacoes/nova')}
                className="inline-flex items-center gap-2"
                trackingId="essay-empty-create-button"
                trackingProperties={{
                  action: 'create_first_essay',
                  page: 'essays_list',
                  context: 'empty_state'
                }}
              >
                <Plus className="h-5 w-5" />
                <AdaptiveText text="Criar Redação" isUpperCase={isUpperCase} />
              </Button>
            )}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-3 gap-6 p-6">
            {filteredEssays.map((essay) => (
              <div
                key={essay.id}
                className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden cursor-pointer hover:shadow-md transition"
                onClick={() => navigate(`/aluno/redacoes/${essay.id}`)}
              >
                <div className="p-6">
                  <h3 className="font-medium text-gray-900 mb-2">
                    <AdaptiveText text={essay.title} isUpperCase={isUpperCase} />
                  </h3>
                  <div className="flex items-center gap-2 text-sm text-gray-600 mb-4">
                    <AdaptiveText text={essay.essay_type?.title} isUpperCase={isUpperCase} />
                    <span>•</span>
                    <AdaptiveText text={essay.essay_genre?.title} isUpperCase={isUpperCase} />
                  </div>
                  <div className="flex items-center justify-between text-sm text-gray-500">
                    <span>{new Date(essay.created_at).toLocaleDateString('pt-BR')}</span>
                    {getStatusBadge(essay.status)}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
} 