import React from 'react';
import { ArrowLeft, ArrowRight, Mic, Volume2, Share2, ChevronDown, ChevronUp, Loader2 } from 'lucide-react';
import { AudioRecorder } from '../../components/story/AudioRecorder';
import { StoryMetrics } from '../../components/story/StoryMetrics';
import type { StoryRecording } from '../../types/database';

// Separar dados mock em arquivo próprio
const DEMO_DATA = {
  recording: {
    id: 'demo-recording',
    fluency_score: 85,
    pronunciation_score: 90,
    accuracy_score: 88,
    comprehension_score: 92,
    words_per_minute: 120,
    pause_count: 3,
    error_count: 2,
    self_corrections: 1,
    strengths: [
      'Ótima pronúncia das palavras',
      'Boa velocidade de leitura',
      'Excelente compreensão do texto'
    ],
    improvements: [
      'Reduzir pequenas pausas entre frases',
      'Praticar palavras mais complexas'
    ],
    suggestions: 'Continue praticando a leitura em voz alta regularmente',
    created_at: new Date().toISOString(),
    processed_at: new Date().toISOString()
  },
  story: {
    id: 'demo',
    student_id: 'demo',
    title: 'Uma Aventura Educacional',
    content: {
      pages: [
        {
          text: 'Bem-vindo à demonstração do Leiturama! Aqui você pode ver como funciona nossa plataforma de leitura interativa...',
          image: 'https://images.unsplash.com/photo-1472162072942-cd5147eb3902?auto=format&fit=crop&q=80&w=800&h=600',
        },
        {
          text: 'Com histórias interativas e educativas, seus alunos aprenderão de forma divertida e envolvente. Cada história é uma nova aventura!',
          image: 'https://images.unsplash.com/photo-1519681393784-d120267933ba?auto=format&fit=crop&q=80&w=800&h=600',
        }
      ]
    }
  }
};

// Componente para imagem com loading
function ImageWithLoading({ src, alt }: { src: string; alt: string }) {
  const [isLoading, setIsLoading] = React.useState(true);

  return (
    <div className="relative aspect-video bg-gray-50">
      {isLoading && (
        <div className="absolute inset-0 flex items-center justify-center">
          <Loader2 className="w-8 h-8 text-purple-600 animate-spin" />
        </div>
      )}
      <img
        src={src}
        alt={alt}
        className={`w-full h-full object-cover transition-opacity duration-300 ${
          isLoading ? 'opacity-0' : 'opacity-100'
        }`}
        onLoad={() => setIsLoading(false)}
      />
    </div>
  );
}

// Componente para navegação entre páginas
function PageNavigation({ 
  currentPage, 
  totalPages, 
  onPrevious, 
  onNext 
}: { 
  currentPage: number;
  totalPages: number;
  onPrevious: () => void;
  onNext: () => void;
}) {
  return (
    <div className="flex justify-between items-center mt-8 pt-6 border-t border-gray-200">
      <button
        onClick={onPrevious}
        disabled={currentPage === 0}
        className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-900 disabled:opacity-50 transition"
      >
        <ArrowLeft className="h-5 w-5" />
        Anterior
      </button>

      <span className="text-sm font-medium text-gray-500">
        Página {currentPage + 1} de {totalPages}
      </span>

      <button
        onClick={onNext}
        disabled={currentPage === totalPages - 1}
        className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-900 disabled:opacity-50 transition"
      >
        Próxima
        <ArrowRight className="h-5 w-5" />
      </button>
    </div>
  );
}

export function StoryPageDemo(): JSX.Element {
  const [currentPage, setCurrentPage] = React.useState(0);
  const [isPlaying, setIsPlaying] = React.useState(false);
  const [showMetrics, setShowMetrics] = React.useState(false);
  const [isRecording, setIsRecording] = React.useState(false);

  const handleShare = () => {
    alert('Funcionalidade de compartilhamento disponível apenas na versão completa!');
  };

  // Simula o processo de gravação e análise
  const handleRecordingComplete = () => {
    setIsRecording(true);
    setTimeout(() => {
      setIsRecording(false);
      setShowMetrics(true);
    }, 3000); // Simula 3 segundos de "processamento"
  };

  return (
    <div className="min-h-screen bg-gradient-to-b from-purple-50 to-white py-12">
      <div className="max-w-4xl mx-auto px-4 space-y-8">
        {/* Header */}
        <header className="flex justify-between items-center">
          <button
            onClick={() => window.history.back()}
            className="flex items-center gap-2 text-gray-600 hover:text-gray-900 transition"
          >
            <ArrowLeft className="h-5 w-5" />
            Voltar
          </button>

          <div className="flex items-center gap-4">
            <button
              onClick={handleShare}
              className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-900 transition"
            >
              <Share2 className="h-5 w-5" />
              Compartilhar
            </button>
            <button
              onClick={() => setIsPlaying(!isPlaying)}
              className="flex items-center gap-2 px-4 py-2 text-gray-600 hover:text-gray-900 transition"
            >
              <Volume2 className="h-5 w-5" />
              {isPlaying ? 'Pausar' : 'Ouvir'}
            </button>
          </div>
        </header>

        {/* História com Imagem */}
        <main className="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
          <ImageWithLoading
            src={DEMO_DATA.story.content.pages[currentPage].image}
            alt={`Página ${currentPage + 1}`}
          />

          <div className="p-8">
            <h1 className="text-3xl font-bold text-gray-900 mb-6">
              {DEMO_DATA.story.title}
            </h1>
            
            <p className="text-xl leading-relaxed text-gray-700 mb-8">
              {DEMO_DATA.story.content.pages[currentPage].text}
            </p>

            <div className="flex items-center gap-4">
              <button
                onClick={handleRecordingComplete}
                disabled={isRecording}
                className={`flex items-center gap-2 px-6 py-3 rounded-lg text-white transition
                  ${isRecording 
                    ? 'bg-gray-400 cursor-not-allowed' 
                    : 'bg-purple-600 hover:bg-purple-700'}`}
              >
                <Mic className="h-5 w-5" />
                {isRecording ? 'Processando...' : 'Gravar Leitura'}
              </button>
              {isRecording && (
                <div className="flex items-center gap-2 text-gray-600">
                  <Loader2 className="h-5 w-5 animate-spin" />
                  Analisando sua leitura...
                </div>
              )}
            </div>

            <PageNavigation
              currentPage={currentPage}
              totalPages={DEMO_DATA.story.content.pages.length}
              onPrevious={() => setCurrentPage(p => Math.max(0, p - 1))}
              onNext={() => setCurrentPage(p => Math.min(DEMO_DATA.story.content.pages.length - 1, p + 1))}
            />
          </div>
        </main>

        {/* Dashboard de Métricas Condicional */}
        {showMetrics && (
          <section className="space-y-6">
            <h2 className="text-2xl font-bold text-gray-900">
              Dashboard de Leitura
            </h2>

            <StoryMetrics 
              data={{
                metrics: {
                  fluency: DEMO_DATA.recording.fluency_score,
                  pronunciation: DEMO_DATA.recording.pronunciation_score,
                  accuracy: DEMO_DATA.recording.accuracy_score,
                  comprehension: DEMO_DATA.recording.comprehension_score
                },
                feedback: {
                  strengths: DEMO_DATA.recording.strengths,
                  improvements: DEMO_DATA.recording.improvements,
                  suggestions: DEMO_DATA.recording.suggestions
                },
                details: {
                  wordsPerMinute: DEMO_DATA.recording.words_per_minute,
                  pauseCount: DEMO_DATA.recording.pause_count,
                  errorCount: DEMO_DATA.recording.error_count,
                  selfCorrections: DEMO_DATA.recording.self_corrections
                }
              }}
              isLoading={false}
            />
          </section>
        )}

        {/* CTAs */}
        <section className="border-t border-gray-200 pt-8 mt-12">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 text-center">
              <h3 className="text-xl font-bold text-gray-900 mb-4">
                Para Escolas
              </h3>
              <p className="text-gray-600 mb-6">
                Transforme a experiência de leitura na sua escola com nossa plataforma educacional.
              </p>
              <button
                onClick={() => window.location.href = '/register/school'}
                className="w-full px-6 py-3 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition"
              >
                Começar a Usar na Minha Escola
              </button>
            </div>

            <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 text-center">
              <h3 className="text-xl font-bold text-gray-900 mb-4">
                Para Pais
              </h3>
              <p className="text-gray-600 mb-6">
                Acompanhe e incentive o desenvolvimento da leitura do seu filho de forma interativa.
              </p>
              <button
                onClick={() => window.location.href = '/register/parent'}
                className="w-full px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition"
              >
                Quero Usar com Meu Filho
              </button>
            </div>
          </div>
        </section>
      </div>
    </div>
  );
} 