import { useState, useEffect } from "react";
import { ChatHeader } from "@/components/ChatHeader";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { Mic, Download, Trash2, Search, ChevronLeft, ChevronRight } from "lucide-react";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Pagination,
  PaginationContent,
  PaginationItem,
} from "@/components/ui/pagination";
import { useToast } from "@/hooks/use-toast";
import { audioGenerationService, VOICE_OPTIONS, VoiceType, AudioRecord } from "@/services/audioGeneration";

export const GenerationView = () => {
  const [textToSpeech, setTextToSpeech] = useState("");
  const [isProcessing, setIsProcessing] = useState(false);
  const [selectedVoice, setSelectedVoice] = useState<VoiceType>("alloy");
  const [lastGeneratedAudio, setLastGeneratedAudio] = useState<AudioRecord | null>(null);
  const [audioHistory, setAudioHistory] = useState<AudioRecord[]>([]);
  const [isLoadingAudios, setIsLoadingAudios] = useState(false);
  const [audioSearchQuery, setAudioSearchQuery] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [perPage, setPerPage] = useState(10);
  const { toast } = useToast();

  // Carrega áudios do banco de dados
  const loadAudios = async (page: number = currentPage, limit: number = perPage) => {
    setIsLoadingAudios(true);
    try {
      const fetchedAudios = await audioGenerationService.getAudios(undefined, page, limit);

      // Garante que sempre seja um array
      if (Array.isArray(fetchedAudios)) {
        setAudioHistory(fetchedAudios);
      } else {
        console.warn('Resposta da API não é um array:', fetchedAudios);
        setAudioHistory([]);
      }
    } catch (error: any) {
      console.error('Erro ao carregar áudios:', error);
      toast({
        title: "Erro ao carregar histórico",
        description: error.message || "Não foi possível carregar o histórico de áudios.",
        variant: "destructive",
      });
      setAudioHistory([]);
    } finally {
      setIsLoadingAudios(false);
    }
  };

  // Carrega áudios ao montar e quando a paginação mudar
  useEffect(() => {
    loadAudios();
  }, [currentPage, perPage]);

  const handleGenerateAudio = async () => {
    // Valida o texto antes de enviar
    const validation = audioGenerationService.validateText(textToSpeech);
    if (!validation.valid) {
      toast({
        title: "Texto inválido",
        description: validation.error,
        variant: "destructive",
      });
      return;
    }

    setIsProcessing(true);

    try {
      // Chama o serviço de geração de áudio
      const response = await audioGenerationService.generateAudio({
        message: textToSpeech,
        voice: selectedVoice,
      });

      // Verifica se a geração foi bem-sucedida
      if (response.success) {
        console.log('URL do áudio gerado:', response.audio_url);

        // Cria objeto do áudio recém-gerado para exibição imediata
        const newGeneratedAudio: AudioRecord = {
          id: response.audio_generation_id,
          user_email: '',
          estabelecimento_id: 0,
          input_text: response.message,
          model: 'tts-1',
          voice: selectedVoice,
          audio_url: response.audio_url,
          duration_seconds: null,
          file_size: 0,
          cost_usd: '0',
          created_at: new Date().toISOString(),
        };

        // Salva o último áudio gerado para exibição
        setLastGeneratedAudio(newGeneratedAudio);

        toast({
          title: "Áudio gerado com sucesso",
          description: `Voz: ${VOICE_OPTIONS[selectedVoice].label}`,
        });

        // Limpa o campo de texto após sucesso
        setTextToSpeech("");

        // Recarrega a lista de áudios (sem aguardar para não bloquear a UI)
        loadAudios(1, perPage);
        setCurrentPage(1);
      } else {
        throw new Error('Erro ao gerar áudio');
      }
    } catch (error: any) {
      console.error('Erro na geração de áudio:', error);

      toast({
        title: "Erro na geração",
        description: error.message || "Não foi possível gerar o áudio. Tente novamente.",
        variant: "destructive",
      });
    } finally {
      setIsProcessing(false);
    }
  };

  const handleDownloadAudio = async (audio: AudioRecord) => {
    const filename = `audio_${audio.voice}_${new Date(audio.created_at).getTime()}.mp3`;
    try {
      await audioGenerationService.downloadAudioFile(audio.audio_url, filename);
      toast({
        title: "Download iniciado",
        description: "O arquivo de áudio está sendo baixado.",
      });
    } catch (error: unknown) {
      const message =
        error && typeof error === "object" && "message" in error ? String((error as { message: string }).message) : "Não foi possível baixar o áudio.";
      toast({
        title: "Erro ao baixar",
        description: message,
        variant: "destructive",
      });
    }
  };

  const handleDeleteAudio = async (audioId: string) => {
    try {
      const result = await audioGenerationService.deleteAudio(audioId);

      if (result.success) {
        toast({
          title: "Áudio removido",
          description: "O áudio foi removido com sucesso.",
        });

        // Se o áudio deletado for o último gerado, limpa o preview
        if (lastGeneratedAudio && lastGeneratedAudio.id === audioId) {
          setLastGeneratedAudio(null);
        }

        // Recarrega a lista de áudios
        await loadAudios();
      } else {
        throw new Error(result.message || 'Erro ao deletar áudio');
      }
    } catch (error: any) {
      console.error('Erro ao deletar áudio:', error);
      toast({
        title: "Erro ao remover",
        description: error.message || "Não foi possível remover o áudio.",
        variant: "destructive",
      });
    }
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const handlePerPageChange = (value: string) => {
    setPerPage(parseInt(value));
    setCurrentPage(1);
  };

  const filteredAudios = Array.isArray(audioHistory)
    ? audioHistory.filter(item =>
        (VOICE_OPTIONS[item.voice]?.label || item.voice).toLowerCase().includes(audioSearchQuery.toLowerCase()) ||
        item.input_text.toLowerCase().includes(audioSearchQuery.toLowerCase())
      )
    : [];

  return (
    <div className="flex flex-col h-full pb-16 md:pb-0">
      <ChatHeader />

      <ScrollArea className="flex-1">
        <div className="max-w-4xl mx-auto p-3 md:p-6">
          <Tabs defaultValue="generation" className="space-y-4 md:space-y-6">
            <TabsList className="grid w-full grid-cols-2 glass-effect text-xs md:text-sm">
              <TabsTrigger value="generation" className="text-xs md:text-sm">
                Geração
              </TabsTrigger>
              <TabsTrigger value="history" className="text-xs md:text-sm">
                Histórico
              </TabsTrigger>
            </TabsList>

            <TabsContent value="generation" className="space-y-6">
              <div className="glass-effect rounded-xl p-6 space-y-4">
                <h3 className="text-lg font-semibold">
                  Converter Texto em Voz
                </h3>

                <div className="space-y-2">
                  <label className="text-sm font-medium">
                    Digite o texto para converter
                  </label>
                  <Textarea
                    value={textToSpeech}
                    onChange={(e) => setTextToSpeech(e.target.value)}
                    placeholder="Digite o texto que deseja converter em fala..."
                    className="min-h-[120px] resize-none"
                  />
                </div>

                <div className="space-y-4">
                  <div className="space-y-2">
                    <label className="text-sm font-medium">Tipo de Voz</label>
                    <Select value={selectedVoice} onValueChange={(value) => setSelectedVoice(value as VoiceType)}>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        {Object.entries(VOICE_OPTIONS).map(([key, voice]) => (
                          <SelectItem key={key} value={key}>
                            {voice.label} - {voice.gender}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="bg-muted/30 rounded-lg p-4 space-y-2">
                    <div className="flex items-center justify-between">
                      <p className="text-sm font-medium">{VOICE_OPTIONS[selectedVoice].label}</p>
                      <span className="text-xs text-muted-foreground">Modelo: OpenAI TTS-1</span>
                    </div>
                    <p className="text-xs text-muted-foreground">
                      <strong>Estilo:</strong> {VOICE_OPTIONS[selectedVoice].style}
                    </p>
                    <p className="text-xs text-muted-foreground">
                      {VOICE_OPTIONS[selectedVoice].description}
                    </p>
                  </div>

                  <Button
                    onClick={handleGenerateAudio}
                    disabled={!textToSpeech.trim() || isProcessing}
                    className="gap-2 cyber-glow w-full"
                    size="lg"
                  >
                    <Mic className="w-4 h-4" />
                    {isProcessing ? "Gerando..." : "Gerar Áudio"}
                  </Button>
                </div>

                {isProcessing && (
                  <div className="bg-muted/30 rounded-lg p-6 flex items-center justify-center gap-3">
                    <div className="w-8 h-8 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
                    <p className="text-sm font-medium">
                      Gerando áudio...
                    </p>
                  </div>
                )}
              </div>

              {lastGeneratedAudio && (
                <div className="glass-effect rounded-xl p-6 space-y-4">
                  <div className="flex items-center justify-between">
                    <div>
                      <h4 className="font-semibold">Áudio Gerado</h4>
                      <p className="text-sm text-muted-foreground">
                        Voz: {VOICE_OPTIONS[lastGeneratedAudio.voice]?.label || lastGeneratedAudio.voice}
                      </p>
                    </div>
                    <div className="flex gap-2">
                      <Button
                        type="button"
                        size="sm"
                        variant="outline"
                        className="gap-1"
                        onClick={() => void handleDownloadAudio(lastGeneratedAudio)}
                      >
                        <Download className="w-3 h-3" />
                        Baixar
                      </Button>
                      <Button
                        size="sm"
                        variant="destructive"
                        className="gap-1"
                        onClick={() => handleDeleteAudio(lastGeneratedAudio.id)}
                      >
                        <Trash2 className="w-3 h-3" />
                        Excluir
                      </Button>
                    </div>
                  </div>

                  <div className="bg-muted/30 rounded-lg p-4">
                    <p className="text-sm mb-3">{lastGeneratedAudio.input_text}</p>
                    <audio
                      key={lastGeneratedAudio.id}
                      controls
                      className="w-full"
                      preload="metadata"
                    >
                      <source src={lastGeneratedAudio.audio_url} type="audio/mpeg" />
                      Seu navegador não suporta o elemento de áudio.
                    </audio>
                  </div>
                </div>
              )}
            </TabsContent>

            <TabsContent value="history" className="space-y-4">
              {/* Search and Filters */}
              <div className="flex flex-col md:flex-row gap-3">
                <div className="relative flex-1">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
                  <Input
                    value={audioSearchQuery}
                    onChange={(e) => setAudioSearchQuery(e.target.value)}
                    placeholder="Buscar por voz ou conteúdo..."
                    className="pl-9"
                  />
                </div>
                <Select value={perPage.toString()} onValueChange={handlePerPageChange}>
                  <SelectTrigger className="w-full md:w-[180px]">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent className="glass-effect bg-popover border-border z-50">
                    <SelectItem value="5">5 por página</SelectItem>
                    <SelectItem value="10">10 por página</SelectItem>
                    <SelectItem value="20">20 por página</SelectItem>
                    <SelectItem value="50">50 por página</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              {/* Loading State */}
              {isLoadingAudios ? (
                <div className="glass-effect rounded-xl p-12 flex flex-col items-center justify-center space-y-4">
                  <div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
                  <p className="text-muted-foreground">Carregando áudios...</p>
                </div>
              ) : (
                <>
                  {filteredAudios.length === 0 ? (
                    <div className="glass-effect rounded-xl p-12 text-center">
                      <Mic className="w-12 h-12 mx-auto mb-4 text-muted-foreground opacity-50" />
                      <p className="text-muted-foreground">
                        {audioSearchQuery ? 'Nenhum áudio encontrado' : 'Nenhum áudio gerado ainda'}
                      </p>
                    </div>
                  ) : (
                    <>
                      <div className="space-y-3">
                        {filteredAudios.map((audio) => (
                          <div key={audio.id} className="glass-effect rounded-lg p-4 space-y-3">
                            <div className="flex items-start justify-between gap-2">
                              <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-2">
                                  <h4 className="font-medium">
                                    Voz: {VOICE_OPTIONS[audio.voice]?.label || audio.voice}
                                  </h4>
                                </div>
                                <p className="text-xs text-muted-foreground">
                                  {new Date(audio.created_at).toLocaleDateString('pt-BR')} às{' '}
                                  {new Date(audio.created_at).toLocaleTimeString('pt-BR')}
                                </p>
                              </div>
                              <div className="flex gap-2">
                                <Button
                                  type="button"
                                  size="sm"
                                  variant="ghost"
                                  onClick={() => void handleDownloadAudio(audio)}
                                >
                                  <Download className="w-4 h-4" />
                                </Button>
                                <Button
                                  size="sm"
                                  variant="ghost"
                                  onClick={() => handleDeleteAudio(audio.id)}
                                >
                                  <Trash2 className="w-4 h-4" />
                                </Button>
                              </div>
                            </div>
                            <p className="text-sm text-muted-foreground line-clamp-2">
                              {audio.input_text}
                            </p>
                            <audio
                              key={audio.id}
                              controls
                              className="w-full"
                              preload="metadata"
                            >
                              <source src={audio.audio_url} type="audio/mpeg" />
                            </audio>
                          </div>
                        ))}
                      </div>

                      {/* Pagination */}
                      {!audioSearchQuery && audioHistory.length >= perPage && (
                        <div className="flex items-center justify-center gap-4 mt-6">
                          <Pagination>
                            <PaginationContent>
                              <PaginationItem>
                                <Button
                                  variant="outline"
                                  size="sm"
                                  onClick={() => handlePageChange(currentPage - 1)}
                                  disabled={currentPage === 1}
                                  className="gap-1"
                                >
                                  <ChevronLeft className="h-4 w-4" />
                                  <span className="hidden md:inline">Anterior</span>
                                </Button>
                              </PaginationItem>

                              <PaginationItem>
                                <span className="text-sm text-muted-foreground px-4">
                                  Página {currentPage}
                                </span>
                              </PaginationItem>

                              <PaginationItem>
                                <Button
                                  variant="outline"
                                  size="sm"
                                  onClick={() => handlePageChange(currentPage + 1)}
                                  disabled={audioHistory.length < perPage}
                                  className="gap-1"
                                >
                                  <span className="hidden md:inline">Próxima</span>
                                  <ChevronRight className="h-4 w-4" />
                                </Button>
                              </PaginationItem>
                            </PaginationContent>
                          </Pagination>
                        </div>
                      )}
                    </>
                  )}
                </>
              )}
            </TabsContent>
          </Tabs>
        </div>
      </ScrollArea>
    </div>
  );
};
