import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { supabase } from '@/lib/supabase';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { ArrowLeft, Sparkles } from 'lucide-react';
import { useSession } from '@/hooks/useSession';
import { useUppercasePreference } from '@/hooks/useUppercasePreference';
import { AdaptiveText, AdaptiveTitle, AdaptiveParagraph } from '@/components/ui/adaptive-text';
import { TextCaseToggle } from '@/components/ui/text-case-toggle';
import { cn } from '@/lib/utils';

interface EssayType {
  id: string;
  title: string;
  description: string;
  icon: string;
}

interface EssayGenre {
  id: string;
  title: string;
  description: string;
  icon: string;
  requirements: {
    min_words: number;
    max_words: number;
    required_elements: string[];
  };
}

export function NewEssay() {
  const navigate = useNavigate();
  const [step, setStep] = useState<'type' | 'genre'>('type');
  const [selectedType, setSelectedType] = useState<EssayType | null>(null);
  const [types, setTypes] = useState<EssayType[]>([]);
  const [genres, setGenres] = useState<EssayGenre[]>([]);
  const [loading, setLoading] = useState(true);
  const { session } = useSession();
  const { isUpperCase, toggleUppercase, isLoading } = useUppercasePreference(session?.user?.id);

  useEffect(() => {
    loadTypes();
  }, []);

  // Carregar tipos textuais
  async function loadTypes() {
    try {
      const { data, error } = await supabase
        .from('essay_types')
        .select('*')
        .eq('active', true);

      if (error) throw error;
      setTypes(data || []);
    } catch (error) {
      console.error('Erro ao carregar tipos:', error);
    } finally {
      setLoading(false);
    }
  }

  // Carregar gêneros do tipo selecionado
  async function loadGenres(typeId: string) {
    try {
      const { data, error } = await supabase
        .from('essay_genres')
        .select('*')
        .eq('type_id', typeId)
        .eq('active', true);

      if (error) throw error;
      setGenres(data || []);
    } catch (error) {
      console.error('Erro ao carregar gêneros:', error);
    }
  }

  // Criar nova redação
  async function createEssay(genreId: string) {
    try {
      const { data: { user } } = await supabase.auth.getUser();
      if (!user) throw new Error('Usuário não autenticado');

      const { data, error } = await supabase
        .from('student_essays')
        .insert({
          student_id: user.id,
          type_id: selectedType!.id,
          genre_id: genreId,
          status: 'draft',
          title: 'Nova Redação',
          content: ''
        })
        .select()
        .single();

      if (error) throw error;
      navigate(`/aluno/redacoes/${data.id}`);
    } catch (error) {
      console.error('Erro ao criar redação:', error);
    }
  }

  // Renderizar seleção de tipo textual
  function renderTypeSelection() {
    return (
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {types.map((type) => (
          <Card 
            key={type.id}
            className={cn(
              "cursor-pointer hover:shadow-lg transition-all duration-200",
              "bg-white border border-gray-200",
              selectedType?.id === type.id && "ring-2 ring-purple-600 bg-purple-50"
            )}
            onClick={() => {
              setSelectedType(type);
              loadGenres(type.id);
              setStep('genre');
            }}
          >
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <div className="p-2 bg-purple-100 rounded-lg">
                  <span className="text-2xl">{type.icon}</span>
                </div>
                <AdaptiveText
                  text={type.title}
                  isUpperCase={isUpperCase}
                  className="font-bold"
                />
              </CardTitle>
              <CardDescription>
                <AdaptiveText
                  text={type.description}
                  isUpperCase={isUpperCase}
                  className="text-gray-600"
                />
              </CardDescription>
            </CardHeader>
          </Card>
        ))}
      </div>
    );
  }

  // Renderizar seleção de gênero textual
  function renderGenreSelection() {
    return (
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {genres.map((genre) => (
          <Card 
            key={genre.id}
            className="cursor-pointer hover:shadow-lg transition-all duration-200 bg-white border border-gray-200"
            onClick={() => createEssay(genre.id)}
          >
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <div className="p-2 bg-purple-100 rounded-lg">
                  <span className="text-2xl">{genre.icon}</span>
                </div>
                <AdaptiveText
                  text={genre.title}
                  isUpperCase={isUpperCase}
                  className="font-bold"
                />
              </CardTitle>
              <CardDescription>
                <AdaptiveText
                  text={genre.description}
                  isUpperCase={isUpperCase}
                  className="text-gray-600"
                />
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <div className="bg-purple-50 p-4 rounded-lg border border-purple-100">
                  <h4 className="text-sm font-medium text-purple-900 mb-2">Requisitos</h4>
                  <div className="space-y-2 text-sm text-purple-800">
                    <p>Mínimo: {genre.requirements?.min_words || 0} palavras</p>
                    <p>Máximo: {genre.requirements?.max_words || 'Sem limite'} palavras</p>
                    {genre.requirements?.required_elements && genre.requirements.required_elements.length > 0 && (
                      <>
                        <p className="mt-2 font-medium">Elementos necessários:</p>
                        <ul className="list-disc list-inside space-y-1">
                          {genre.requirements.required_elements.map((element, index) => (
                            <li key={index}>
                              <AdaptiveText
                                text={element}
                                isUpperCase={isUpperCase}
                              />
                            </li>
                          ))}
                        </ul>
                      </>
                    )}
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    );
  }

  return (
    <div className="container mx-auto p-6">
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
        <div className="flex items-center gap-3 mb-8">
          <div className="p-2 bg-purple-100 rounded-lg">
            <Sparkles className="h-6 w-6 text-purple-600" />
          </div>
          <div>
            <AdaptiveTitle
              text="Nova Redação"
              isUpperCase={isUpperCase}
              className="text-2xl font-bold text-gray-900"
            />
            <AdaptiveParagraph
              text={step === 'type' 
                ? "Selecione o tipo textual para começar"
                : "Escolha o gênero textual da sua redação"}
              isUpperCase={isUpperCase}
              className="text-gray-600"
            />
          </div>
          <TextCaseToggle
            isUpperCase={isUpperCase}
            onToggle={toggleUppercase}
            isLoading={isLoading}
            className="ml-auto"
          />
        </div>

        {step === 'genre' && (
          <Button 
            variant="ghost" 
            onClick={() => setStep('type')}
            className="mb-6"
            trackingId="essay-new-back-button"
            trackingProperties={{
              action: 'back_to_type_selection',
              current_step: 'genre',
              page: 'new_essay'
            }}
          >
            <ArrowLeft className="mr-2 h-4 w-4" />
            Voltar para tipos textuais
          </Button>
        )}

        {loading ? (
          <div className="animate-pulse space-y-4">
            <div className="h-48 bg-gray-100 rounded-lg" />
            <div className="h-48 bg-gray-100 rounded-lg" />
            <div className="h-48 bg-gray-100 rounded-lg" />
          </div>
        ) : step === 'type' ? (
          renderTypeSelection()
        ) : (
          renderGenreSelection()
        )}
      </div>
    </div>
  );
} 