"use client"

import { useRef, useState, useEffect } from "react"
import Link from "next/link"
import { ChevronLeft, ChevronRight } from "lucide-react"
import { Layers, Code2, Cloud, ArrowRight } from "lucide-react"
import { AnimatedWrapper } from "@/components/animated-wrapper"
import { SectionTitle } from "@/components/section-title"
import { GlassCard } from "@/components/glass-card"
import { Button } from "@/components/ui/button"

interface Service {
    icon: React.ReactNode
    title: string
    description: string
    link: string
    features?: string[]
}

interface ServicesData {
    sectionId: string
    overline: string
    title: string
    subtitle?: string
    services: Service[]
}

// Dados dos serviços - separados da lógica de apresentação
const defaultServicesData: ServicesData = {
    sectionId: "servicos",
    overline: "Nossos Serviços",
    title: "Soluções Tecnológicas que Transformam Negócios",
    subtitle: "Desenvolvemos sistemas inovadores e robustos que otimizam processos, aumentam a produtividade e impulsionam o crescimento da sua empresa.",
    services: [
        {
            icon: <Layers size={32} className="text-primary" />,
            title: "GADM ERP",
            description: "Sistema de gestão empresarial completo e integrado, desenvolvido para automatizar e otimizar todos os processos da sua empresa, desde o financeiro até o operacional.",
            link: "#gadm",
            features: ["Gestão Financeira Completa", "Controle de Estoque em Tempo Real", "Relatórios Gerenciais Avançados", "Módulos Integrados", "Suporte Multiplataforma"]
        },
        {
            icon: <Layers size={32} className="text-primary" />,
            title: "IS - ENTREGAS",
            description: "Solução especializada para otimizar a logística de entregas, com rastreamento em tempo real, roteirização inteligente e controle completo da operação.",
            link: "#is-entregas",
            features: ["Rastreamento GPS", "Roteirização Automática", "Controle de Status", "Notificações em Tempo Real", "Relatórios de Performance"]
        },
        {
            icon: <Layers size={32} className="text-primary" />,
            title: "IS - VENDAS",
            description: "Aplicativo mobile e web para equipes de vendas, facilitando o processo comercial com catálogo digital, pedidos offline e sincronização automática.",
            link: "#is-vendas",
            features: ["Catálogo Digital Interativo", "Vendas Offline", "Sincronização Automática", "Gestão de Clientes", "Comissões e Metas"]
        },
        {
            icon: <Code2 size={32} className="text-primary" />,
            title: "Desenvolvimento Web",
            description: "Criamos sites modernos, sistemas web personalizados e aplicações responsivas com foco na experiência do usuário e performance excepcional.",
            link: "#webdev",
            features: ["Design Responsivo", "Performance Otimizada", "SEO Avançado", "Tecnologias Modernas", "Suporte Contínuo"]
        },
        {
            icon: <Cloud size={32} className="text-primary" />,
            title: "GADM Online",
            description: "Versão na nuvem do nosso ERP, oferecendo acesso seguro de qualquer lugar, com alta disponibilidade, backup automático e escalabilidade garantida.",
            link: "#gadmonline",
            features: ["Acesso 24/7 Global", "Backup Automático Diário", "Multiusuário Simultâneo", "Segurança Avançada", "Atualizações Automáticas"]
        },
    ]
}

// Componente para um card de serviço individual
interface ServiceCardProps {
    service: Service
    index: number
    showFeatures?: boolean
}

function ServiceCard({ service, index, showFeatures = false }: ServiceCardProps) {
    return (
        <div className="flex-shrink-0 w-80 md:w-96">
            <AnimatedWrapper delay={index * 0.1}>
                <GlassCard className="h-auto min-h-[280px] flex flex-col group hover:shadow-xl hover:shadow-primary/10 transition-all duration-300 border-transparent hover:border-primary/20 p-6 cursor-pointer">
                    {/* Ícone com efeito hover */}
                    <div className="mb-4 transform group-hover:scale-110 group-hover:rotate-3 transition-transform duration-300">
                        <div className="p-3 rounded-xl bg-primary/10 group-hover:bg-primary/20 transition-colors duration-300 w-fit">
                            {service.icon}
                        </div>
                    </div>

                    {/* Título */}
                    <h3 className="text-xl font-semibold text-foreground mb-3 group-hover:text-primary transition-colors duration-300">
                        {service.title}
                    </h3>

                    {/* Descrição */}
                    <p className="text-muted-foreground text-sm leading-relaxed mb-6 flex-grow">
                        {service.description}
                    </p>

                    {/* Features opcionais */}
                    {showFeatures && service.features && (
                        <ul className="space-y-2 mb-6">
                            {service.features.map((feature, idx) => (
                                <li key={idx} className="flex items-center text-xs text-muted-foreground">
                                    <span className="w-1.5 h-1.5 bg-primary rounded-full mr-2 flex-shrink-0"></span>
                                    {feature}
                                </li>
                            ))}
                        </ul>
                    )}

                    {/* Call to action - sempre no final */}
                    <div className="mt-auto">
                        <Button
                            asChild
                            variant="link"
                            className="text-primary p-0 self-start hover:text-primary/80 group/btn"
                        >
                            <Link href={service.link} className="flex items-center">
                                <span>Saiba mais</span>
                                <ArrowRight
                                    size={16}
                                    className="ml-2 group-hover/btn:translate-x-1 transition-transform duration-200"
                                />
                            </Link>
                        </Button>
                    </div>
                </GlassCard>
            </AnimatedWrapper>
        </div>
    )
}

// Componente principal da seção
interface ServicesSectionProps {
    data?: ServicesData
    className?: string
    showFeatures?: boolean
    variant?: "default" | "compact" | "detailed"
}

export function ServicesSection({
    data = defaultServicesData,
    className = "",
    showFeatures = false,
    variant = "default"
}: ServicesSectionProps) {
    const scrollContainerRef = useRef<HTMLDivElement>(null)
    const [canScrollLeft, setCanScrollLeft] = useState(false)
    const [canScrollRight, setCanScrollRight] = useState(true)
    const [isDragging, setIsDragging] = useState(false)
    const [startX, setStartX] = useState(0)
    const [scrollLeftStart, setScrollLeftStart] = useState(0)
    const [currentIndex, setCurrentIndex] = useState(0)    // Função para checar se pode fazer scroll
    const checkScrollButtons = () => {
        if (!scrollContainerRef.current) return

        const { scrollLeft, scrollWidth, clientWidth } = scrollContainerRef.current
        setCanScrollLeft(scrollLeft > 0)

        // Para a direita, sempre permitir scroll se ainda há conteúdo
        // Removemos a limitação para permitir scroll além do viewport
        setCanScrollRight(scrollLeft < scrollWidth - clientWidth + 200) // +200px para permitir scroll extra

        // Calcular índice atual baseado na posição do scroll
        const cardWidth = 320 // largura aproximada do card + gap
        const newIndex = Math.round(scrollLeft / cardWidth)
        setCurrentIndex(newIndex)
    }

    // Função para scroll suave para a esquerda
    const scrollLeft = () => {
        if (!scrollContainerRef.current) return

        const cardWidth = 320 // largura aproximada do card + gap
        scrollContainerRef.current.scrollBy({
            left: -cardWidth,
            behavior: 'smooth'
        })
    }

    // Função para scroll suave para a direita
    const scrollRight = () => {
        if (!scrollContainerRef.current) return

        const cardWidth = 320 // largura aproximada do card + gap
        scrollContainerRef.current.scrollBy({
            left: cardWidth,
            behavior: 'smooth'
        })
    }

    // Handlers para drag/touch
    const handleMouseDown = (e: React.MouseEvent) => {
        if (!scrollContainerRef.current) return
        setIsDragging(true)
        setStartX(e.pageX - scrollContainerRef.current.offsetLeft)
        setScrollLeftStart(scrollContainerRef.current.scrollLeft)
    }

    const handleMouseMove = (e: React.MouseEvent) => {
        if (!isDragging || !scrollContainerRef.current) return
        e.preventDefault()
        const x = e.pageX - scrollContainerRef.current.offsetLeft
        const walk = (x - startX) * 1.5 // multiplicador para velocidade
        scrollContainerRef.current.scrollLeft = scrollLeftStart - walk
    }

    const handleMouseUp = () => {
        setIsDragging(false)
    }

    const handleMouseLeave = () => {
        setIsDragging(false)
    }

    // Touch handlers para dispositivos móveis
    const handleTouchStart = (e: React.TouchEvent) => {
        if (!scrollContainerRef.current) return
        setIsDragging(true)
        setStartX(e.touches[0].pageX - scrollContainerRef.current.offsetLeft)
        setScrollLeftStart(scrollContainerRef.current.scrollLeft)
    }

    const handleTouchMove = (e: React.TouchEvent) => {
        if (!isDragging || !scrollContainerRef.current) return
        const x = e.touches[0].pageX - scrollContainerRef.current.offsetLeft
        const walk = (x - startX) * 1.5
        scrollContainerRef.current.scrollLeft = scrollLeftStart - walk
    }

    const handleTouchEnd = () => {
        setIsDragging(false)
    }

    // Effect para inicializar e escutar mudanças de scroll
    useEffect(() => {
        const container = scrollContainerRef.current
        if (!container) return

        checkScrollButtons()

        const handleScroll = () => checkScrollButtons()
        container.addEventListener('scroll', handleScroll)

        // Listener para resize da janela
        const handleResize = () => checkScrollButtons()
        window.addEventListener('resize', handleResize)

        return () => {
            container.removeEventListener('scroll', handleScroll)
            window.removeEventListener('resize', handleResize)
        }
    }, [])

    return (
        <section
            id={data.sectionId}
            className={`py-20 lg:py-28 ${className}`}
        >
            <div className="container mx-auto px-4 sm:px-6 lg:px-8">
                {/* Header da seção */}
                <AnimatedWrapper>
                    <SectionTitle
                        overline={data.overline}
                        title={data.title}
                        subtitle={data.subtitle}
                    />
                </AnimatedWrapper>

                {/* Carousel de serviços */}
                <div className="mt-12 relative">
                    {/* Botões de navegação */}
                    <div className="absolute top-1/2 -translate-y-1/2 left-0 z-20">
                        <button
                            onClick={scrollLeft}
                            disabled={!canScrollLeft}
                            className={`
                                w-12 h-12 rounded-full bg-background/80 dark:bg-background/60 
                                backdrop-blur-md flex items-center justify-center transition-all duration-200
                                hover:bg-background hover:scale-105
                                disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:scale-100
                                ${canScrollLeft ? 'text-foreground hover:text-primary' : 'text-muted-foreground'}
                            `}
                            aria-label="Scroll para a esquerda"
                        >
                            <ChevronLeft size={20} />
                        </button>
                    </div>

                    <div className="absolute top-1/2 -translate-y-1/2 right-0 z-20">
                        <button
                            onClick={scrollRight}
                            disabled={!canScrollRight}
                            className={`
                                w-12 h-12 rounded-full bg-background/80 dark:bg-background/60 
                                backdrop-blur-md flex items-center justify-center transition-all duration-200
                                hover:bg-background hover:scale-105
                                disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:scale-100
                                ${canScrollRight ? 'text-foreground hover:text-primary' : 'text-muted-foreground'}
                            `}
                            aria-label="Scroll para a direita"
                        >
                            <ChevronRight size={20} />
                        </button>
                    </div>                    {/* Gradientes de fade nas bordas */}
                    <div className={`
                        absolute left-0 top-0 bottom-0 w-16 z-10 pointer-events-none
                        bg-gradient-to-r from-background to-transparent
                        transition-opacity duration-300
                        ${canScrollLeft ? 'opacity-100' : 'opacity-0'}
                    `} />

                    {/* Gradient direito sempre visível quando há conteúdo para scroll */}
                    <div className={`
                        absolute right-0 top-0 bottom-0 w-16 z-10 pointer-events-none
                        bg-gradient-to-l from-background to-transparent
                        transition-opacity duration-300
                        ${canScrollRight ? 'opacity-100' : 'opacity-30'}
                    `} />

                    {/* Container do carousel */}
                    <div
                        ref={scrollContainerRef}
                        className={`
                            flex gap-6 overflow-x-auto scrollbar-hide pb-4 px-4 scroll-smooth
                            ${isDragging ? 'cursor-grabbing select-none' : 'cursor-grab'}
                        `}
                        style={{
                            scrollbarWidth: 'none',
                            msOverflowStyle: 'none',
                        }}
                        onMouseDown={handleMouseDown}
                        onMouseMove={handleMouseMove}
                        onMouseUp={handleMouseUp}
                        onMouseLeave={handleMouseLeave}
                        onTouchStart={handleTouchStart}
                        onTouchMove={handleTouchMove}
                        onTouchEnd={handleTouchEnd}
                    >
                        {data.services.map((service, index) => (
                            <ServiceCard
                                key={service.title}
                                service={service}
                                index={index}
                                showFeatures={showFeatures}
                            />
                        ))}

                        {/* Espaço extra generoso para permitir scroll até centralizar o último card */}
                        <div className="flex-shrink-0 w-96" />
                    </div>
                </div>

                {/* CTA adicional opcional */}
                {variant === "detailed" && (
                    <AnimatedWrapper delay={0.4}>
                        <div className="text-center mt-12">
                            <p className="text-muted-foreground mb-6">
                                Não encontrou o que procura? Entre em contato conosco!
                            </p>
                            <Button asChild className="bg-primary hover:bg-primary/90">
                                <Link href="#contato">
                                    Solicitar Orçamento Personalizado
                                </Link>
                            </Button>
                        </div>
                    </AnimatedWrapper>
                )}
            </div>

            {/* CSS para esconder scrollbar e melhorar a experiência */}
            <style jsx>{`
                .scrollbar-hide {
                    -ms-overflow-style: none;
                    scrollbar-width: none;
                }
                .scrollbar-hide::-webkit-scrollbar {
                    display: none;
                }
                
                /* Smooth scroll para navegadores que não suportam scroll-behavior */
                @supports not (scroll-behavior: smooth) {
                    .scroll-smooth {
                        scroll-behavior: auto;
                    }
                }
            `}</style>
        </section>
    )
}

// Exports adicionais para facilitar customização
export { type Service, type ServicesData }