import React from "react";
import { Link } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";
import { Settings, Scale, Lightbulb, Calendar, PenTool, Instagram, Youtube, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader } from "@/components/ui/card";
import { Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious } from "@/components/ui/carousel";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from "@/components/ui/accordion";
import ContentCard from "@/components/ContentCard";
import { fetchContentData } from "@/services/sheetsApi";
import { ContentItem } from "@/types/content";
import Autoplay from "embla-carousel-autoplay";

import SEOHead from "@/components/SEO/SEOHead";
import { createOrganizationSchema, createWebsiteSchema } from "@/utils/seoUtils";

const HomePage = () => {
  const {
    data: content = [],
    isLoading,
    error
  } = useQuery<ContentItem[], Error>({
    queryKey: ['content'],
    queryFn: fetchContentData,
    staleTime: 5 * 60 * 1000,
    gcTime: 30 * 60 * 1000,
    refetchOnWindowFocus: false,
    retry: 1
  });
  
  const getLatestContent = (): ContentItem[] => {
    if (!content || !Array.isArray(content)) return [];
    
    // Parse "Carimbo de data/hora" timestamp for filtering and sorting
    const parseTimestamp = (timestampStr: string): Date => {
      if (!timestampStr) return new Date(0);
      
      // Handle format "DD/MM/YYYY HH:MM:SS" from Google Sheets
      const timestampMatch = timestampStr.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})\s+(\d{1,2}):(\d{2}):(\d{2})$/);
      if (timestampMatch) {
        const [, day, month, year, hour, minute, second] = timestampMatch;
        return new Date(parseInt(year), parseInt(month) - 1, parseInt(day), parseInt(hour), parseInt(minute), parseInt(second));
      }
      
      // Handle format "DD/MM/YYYY" without time
      if (timestampStr.match(/^\d{1,2}\/\d{1,2}\/\d{4}$/)) {
        const [day, month, year] = timestampStr.split('/');
        return new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
      }
      
      return new Date(timestampStr);
    };
    
    const now = new Date();
    const currentMonth = now.getMonth();
    const currentYear = now.getFullYear();
    
    // Calcular mês e ano anterior
    const previousMonth = currentMonth === 0 ? 11 : currentMonth - 1;
    const previousYear = currentMonth === 0 ? currentYear - 1 : currentYear;
    
    // Filtra cards pelo mês do CARIMBO DE DATA/HORA (não da data de publicação)
    // e ordena por carimboDataHora decrescente
    return [...content]
      .filter((item) => {
        const itemDate = parseTimestamp(item.carimboDataHora || "");
        const itemMonth = itemDate.getMonth();
        const itemYear = itemDate.getFullYear();
        
        return (
          (itemMonth === currentMonth && itemYear === currentYear) ||
          (itemMonth === previousMonth && itemYear === previousYear)
        );
      })
      .sort((a, b) => {
        const dateA = parseTimestamp(a.carimboDataHora || "");
        const dateB = parseTimestamp(b.carimboDataHora || "");
        
        return dateB.getTime() - dateA.getTime(); // Ordem decrescente (mais recente primeiro)
      });
  };
  
  if (error) return <div className="text-center py-12">Erro ao carregar conteúdo</div>;
  
  const organizationSchema = createOrganizationSchema();
  const websiteSchema = createWebsiteSchema();
  const combinedSchema = [organizationSchema, websiteSchema];

  return (
    <>
      <SEOHead
        title="GT CIA OAB/RJ — Inteligência Artificial no Direito"
        description="Portal do GT da Comissão de IA da OAB/RJ: conteúdos, cursos gratuitos e recursos sobre IA Generativa, Engenharia de Prompt e Legal Design."
        keywords="inteligência artificial advogados, OAB RJ, engenharia de prompt, IA generativa, legal design, tecnologia jurídica, direito digital, cursos IA gratuitos, Rio de Janeiro"
        canonical="https://gtciaoabrj.ia.br/"
        structuredData={combinedSchema}
      />
      <div className="min-h-screen bg-background">
        <div className="container mx-auto px-4 py-8 mb-2">
          <div className="max-w-4xl mx-auto">
            
            {/* Hero Section */}
            <div className="text-center mb-12">
              <h1 className="text-3xl md:text-5xl font-bold mb-4">
                <span className="text-foreground block">Grupo de Trabalho</span>
                <span className="text-primary block text-sm md:text-3xl text-center px-2 whitespace-nowrap">Engenharia de Prompt, IA Generativa e Legal Design</span>
                <span className="text-muted-foreground text-sm md:text-lg font-medium block mt-2">
                  Comissão de Inteligência Artificial da OAB/RJ
                </span>
              </h1>
              <p className="text-lg text-muted-foreground">
                Inovação, tecnologia e direito unidos para transformar a advocacia brasileira
              </p>
            </div>

            {/* Thematic Cards */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-12">
              <Link to="/dicas-instagram" onClick={() => requestAnimationFrame(() => window.scrollTo(0, 0))}>
                <Card className="text-center hover:shadow-lg transition-shadow h-full bg-card">
                  <CardHeader className="pb-4">
                    <div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <Instagram className="w-6 h-6 text-primary" />
                    </div>
                    <h2 className="font-semibold tracking-tight text-xl text-card-foreground">Dicas de IA no Instagram</h2>
                  </CardHeader>
                  <CardContent>
                    <p className="text-muted-foreground">
                      Ferramentas de IA recomendadas por especialistas
                    </p>
                  </CardContent>
                </Card>
              </Link>

              <Link to="/dicas-youtube" onClick={() => requestAnimationFrame(() => window.scrollTo(0, 0))}>
                <Card className="text-center hover:shadow-lg transition-shadow h-full bg-card">
                  <CardHeader className="pb-4">
                    <div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <Youtube className="w-6 h-6 text-primary" />
                    </div>
                    <h2 className="font-semibold tracking-tight text-xl text-card-foreground">Dicas de IA no YouTube</h2>
                  </CardHeader>
                  <CardContent>
                    <p className="text-muted-foreground">
                      Vídeos de IA recomendados por especialistas
                    </p>
                  </CardContent>
                </Card>
              </Link>

              <Link to="/tematica/engenharia-prompt" onClick={() => requestAnimationFrame(() => window.scrollTo(0, 0))}>
                <Card className="text-center hover:shadow-lg transition-shadow h-full bg-card">
                  <CardHeader className="pb-4">
                    <div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <Lightbulb className="w-6 h-6 text-primary" />
                    </div>
                    <h2 className="font-semibold tracking-tight text-xl text-card-foreground">Engenharia de Prompt</h2>
                  </CardHeader>
                  <CardContent>
                    <p className="text-muted-foreground">
                      Técnicas avançadas para otimizar interações com IA
                    </p>
                  </CardContent>
                </Card>
              </Link>

              <Link to="/tematica/ia-generativa" onClick={() => requestAnimationFrame(() => window.scrollTo(0, 0))}>
                <Card className="text-center hover:shadow-lg transition-shadow h-full bg-card">
                  <CardHeader className="pb-4">
                    <div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <Settings className="w-6 h-6 text-primary" />
                    </div>
                    <h2 className="font-semibold tracking-tight text-xl text-card-foreground">IA Generativa</h2>
                  </CardHeader>
                  <CardContent>
                    <p className="text-muted-foreground">
                      Novidades sobre inteligência artificial generativa
                    </p>
                  </CardContent>
                </Card>
              </Link>

              <Link to="/tematica/ia-juridica" onClick={() => requestAnimationFrame(() => window.scrollTo(0, 0))}>
                <Card className="text-center hover:shadow-lg transition-shadow h-full bg-card">
                  <CardHeader className="pb-4">
                    <div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <Scale className="w-6 h-6 text-primary" />
                    </div>
                    <h2 className="font-semibold tracking-tight text-xl text-card-foreground">IA Jurídica</h2>
                  </CardHeader>
                  <CardContent>
                    <p className="text-muted-foreground">
                      Notícias sobre inteligência artificial para o mundo jurídico
                    </p>
                  </CardContent>
                </Card>
              </Link>

              <Link to="/tematica/legal-design" onClick={() => requestAnimationFrame(() => window.scrollTo(0, 0))}>
                <Card className="text-center hover:shadow-lg transition-shadow h-full bg-card">
                  <CardHeader className="pb-4">
                    <div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <PenTool className="w-6 h-6 text-primary" />
                    </div>
                    <h2 className="font-semibold tracking-tight text-xl text-card-foreground">Legal Design</h2>
                  </CardHeader>
                  <CardContent>
                    <p className="text-muted-foreground">
                      Design centrado no usuário para documentos jurídicos
                    </p>
                  </CardContent>
                </Card>
              </Link>

              <Link to="/tematica/regulacao-ia" onClick={() => requestAnimationFrame(() => window.scrollTo(0, 0))}>
                <Card className="text-center hover:shadow-lg transition-shadow h-full bg-card">
                  <CardHeader className="pb-4">
                    <div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <Calendar className="w-6 h-6 text-primary" />
                    </div>
                    <h2 className="font-semibold tracking-tight text-xl text-card-foreground">Regulação IA</h2>
                  </CardHeader>
                  <CardContent>
                    <p className="text-muted-foreground">
                      Notícias sobre a regulação da IA no Brasil e no mundo
                    </p>
                  </CardContent>
                </Card>
              </Link>

              <Link to="/sobre-o-gt" onClick={() => requestAnimationFrame(() => window.scrollTo(0, 0))}>
                <Card className="text-center hover:shadow-lg transition-shadow h-full bg-card">
                  <CardHeader className="pb-4">
                    <div className="w-12 h-12 bg-primary/10 rounded-lg flex items-center justify-center mx-auto mb-4">
                      <Users className="w-6 h-6 text-primary" />
                    </div>
                    <h2 className="font-semibold tracking-tight text-xl text-card-foreground">Sobre o GT</h2>
                  </CardHeader>
                  <CardContent>
                    <p className="text-muted-foreground">
                      Conheça nossa equipe e missão
                    </p>
                  </CardContent>
                </Card>
              </Link>
            </div>

            {/* Latest News */}
            {!isLoading && content && Array.isArray(content) && content.length > 0 && (
              <div className="mb-12">
                <div className="text-center mb-8">
                  <h2 className="text-3xl font-bold text-primary mb-2">ÚLTIMAS NOTÍCIAS</h2>
                  <p className="text-xl text-muted-foreground">Atualizações da Semana IA</p>
                </div>
                <Carousel
                  className="w-full"
                  plugins={[
                    Autoplay({
                      delay: 3000,
                      stopOnInteraction: true,
                    }),
                  ]}
                  opts={{
                    align: "start",
                    loop: true,
                  }}
                >
                  <CarouselContent className="-ml-1">
                    {getLatestContent().map((item) => (
                      <CarouselItem key={item.id} className="pl-1 md:basis-1/2 lg:basis-1/3">
                        <div className="p-1 h-full">
                          <ContentCard item={item} showTematica={true} />
                        </div>
                      </CarouselItem>
                    ))}
                  </CarouselContent>
                  <CarouselPrevious />
                  <CarouselNext />
                </Carousel>
              </div>
            )}

            {/* Statistics */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-8 text-center mb-0">
              <div>
                <div className="text-4xl font-bold text-primary mb-2">
                  {isLoading ? "..." : content.length}
                </div>
                <p className="text-muted-foreground">Matérias Publicadas</p>
              </div>
              <div>
              <div className="text-4xl font-bold text-primary mb-2">8</div>
                <p className="text-muted-foreground">Temáticas Abordadas</p>
              </div>
              <div>
                <div className="text-4xl font-bold text-primary mb-2">2025</div>
                <p className="text-muted-foreground">Ano de Criação</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default HomePage;