'use client'

import { useEffect, useState } from 'react'
import {
  Container,
  Heading,
  Text,
  VStack,
  Image,
  Badge,
  HStack,
  Spinner,
  Alert,
  AlertIcon,
  Button,
  useColorModeValue,
  Divider,
  Box,
  IconButton,
  Flex,
} from '@chakra-ui/react'
import { useDispatch, useSelector } from 'react-redux'
import { AppDispatch, RootState } from '@/store'
import { fetchPost, fetchPostBySlug, clearCurrentPost } from '@/store/slices/blogSlice'
import Link from 'next/link'
import { FiArrowLeft, FiCalendar, FiUser, FiChevronLeft, FiChevronRight } from 'react-icons/fi'
import { renderHtmlContent } from '@/lib/blogUtils'
import SEO from '@/components/SEO'
import BlogPostSchema from '@/components/BlogPostSchema'

interface BlogPostProps {
  postId?: number
  slug?: string
}

const ImageSlider = ({ images, alt }: { images: string[], alt: string }) => {
  const [currentIndex, setCurrentIndex] = useState(0)

  if (!images || images.length === 0) {
    return (
      <Image
        src="https://via.placeholder.com/800x400?text=Blog+Post"
        alt={alt}
        borderRadius="xl"
        maxH="400px"
        width="100%"
        objectFit="cover"
      />
    )
  }

  if (images.length === 1) {
    return (
      <Image
        src={images[0]}
        alt={alt}
        borderRadius="xl"
        maxH="400px"
        width="100%"
        objectFit="cover"
        fallbackSrc="https://via.placeholder.com/800x400?text=Blog+Post"
      />
    )
  }

  const nextImage = () => {
    setCurrentIndex((prev) => (prev + 1) % images.length)
  }

  const prevImage = () => {
    setCurrentIndex((prev) => (prev - 1 + images.length) % images.length)
  }

  return (
    <Box position="relative" maxH="400px" overflow="hidden" borderRadius="xl">
      <Image
        src={images[currentIndex]}
        alt={`${alt} - Image ${currentIndex + 1}`}
        maxH="400px"
        width="100%"
        objectFit="cover"
        fallbackSrc="https://via.placeholder.com/800x400?text=Blog+Post"
      />

      {/* Navigation arrows */}
      <IconButton
        aria-label="Previous image"
        icon={<FiChevronLeft />}
        position="absolute"
        left={4}
        top="50%"
        transform="translateY(-50%)"
        bg="blackAlpha.600"
        color="white"
        size="lg"
        _hover={{ bg: "blackAlpha.800" }}
        onClick={prevImage}
      />
      <IconButton
        aria-label="Next image"
        icon={<FiChevronRight />}
        position="absolute"
        right={4}
        top="50%"
        transform="translateY(-50%)"
        bg="blackAlpha.600"
        color="white"
        size="lg"
        _hover={{ bg: "blackAlpha.800" }}
        onClick={nextImage}
      />

      {/* Dots indicator */}
      <Flex
        position="absolute"
        bottom={4}
        left="50%"
        transform="translateX(-50%)"
        gap={2}
      >
        {images.map((_, index) => (
          <Box
            key={index}
            w={3}
            h={3}
            bg={index === currentIndex ? "white" : "whiteAlpha.600"}
            borderRadius="full"
            cursor="pointer"
            onClick={() => setCurrentIndex(index)}
          />
        ))}
      </Flex>
    </Box>
  )
}

export default function BlogPost({ postId, slug }: BlogPostProps) {
  const dispatch = useDispatch<AppDispatch>()
  const { currentPost, loading, error } = useSelector((state: RootState) => state.blog)
  const accentColor = '#043F51'

  useEffect(() => {
    // Fetch by slug if available, otherwise by ID
    if (slug) {
      dispatch(fetchPostBySlug(slug) as any)
    } else if (postId) {
      dispatch(fetchPost(postId))
    }

    return () => {
      dispatch(clearCurrentPost())
    }
  }, [dispatch, postId, slug])

  if (loading) {
    return (
      <Container maxW="4xl" py={20}>
        <VStack spacing={8}>
          <Spinner size="xl" color={accentColor} thickness="4px" />
          <Text>Učitavanje članka...</Text>
        </VStack>
      </Container>
    )
  }

  if (error || !currentPost) {
    return (
      <Container maxW="4xl" py={20}>
        <VStack spacing={8}>
          <Alert status="error" borderRadius="lg">
            <AlertIcon />
            {error || 'Članak nije pronađen'}
          </Alert>
          <Link href="/blog">
            <Button
              as="a"
              leftIcon={<FiArrowLeft />}
              bg={accentColor}
              color="white"
              _hover={{ bg: '#055468' }}
            >
              Nazad na blog
            </Button>
          </Link>
        </VStack>
      </Container>
    )
  }

  const pageDescription = currentPost.descriptionMeta || currentPost.excerpt || currentPost.body?.substring(0, 160) || 'AKTIV online knjigovodstveni program'
  const pageImage = currentPost.imageUrl || currentPost.imageUrls?.[0] || 'https://aktiv.rs/images/aktiv-og-image.jpg'
  const pageUrl = `https://aktiv.rs/${currentPost.slug || currentPost.id}`
  const pageKeywords = currentPost.keywords || 'računovodstvo, knjigovodstvo, AKTIV, online knjigovodstvo, digitalno računovodstvo'

  // Get author name from creator object
  const authorName = currentPost.creator?.firstName && currentPost.creator?.lastName
    ? `${currentPost.creator.firstName} ${currentPost.creator.lastName}`
    : currentPost.author || 'AKTIV'

  // Get dates with fallbacks
  const publishedDate = currentPost.createdAt || currentPost.publishedAt || currentPost.creator?.createdAt
  const modifiedDate = currentPost.updatedAt || currentPost.modifiedAt || publishedDate

  return (
    <>
      <SEO
        title={currentPost.title}
        description={pageDescription}
        canonical={pageUrl}
        image={pageImage}
        type="article"
        publishedTime={publishedDate}
        modifiedTime={modifiedDate}
        author={authorName}
        keywords={pageKeywords}
      />

      <BlogPostSchema
        title={currentPost.title}
        description={pageDescription}
        image={pageImage}
        publishedTime={publishedDate}
        modifiedTime={modifiedDate}
        author={authorName}
        url={pageUrl}
      />

      <Container maxW="4xl" py={20}>
        <VStack spacing={8} align="stretch">
          <Link href="/blog">
          <Button
            as="a"
            leftIcon={<FiArrowLeft />}
            variant="ghost"
            alignSelf="start"
            color={accentColor}
            _hover={{ bg: useColorModeValue('gray.100', 'gray.700') }}
          >
            Nazad na blog
          </Button>
        </Link>

        <VStack spacing={6} align="start">
          <Badge bg={accentColor} color="white" variant="solid" alignSelf="start">
            Članak
          </Badge>

          <Heading
            fontSize={{ base: '2xl', sm: '4xl' }}
            fontWeight="bold"
            color={useColorModeValue('gray.700', 'white')}
            lineHeight="shorter"
          >
            {currentPost.title}
          </Heading>

          <HStack spacing={6} color={useColorModeValue('gray.600', 'gray.400')}>
            <HStack spacing={2}>
              <FiUser />
              <Text>
                {currentPost.creator?.firstName && currentPost.creator?.lastName
                  ? `${currentPost.creator.firstName} ${currentPost.creator.lastName}`
                  : currentPost.author || 'AKTIV'}
              </Text>
            </HStack>
            <HStack spacing={2}>
              <FiCalendar />
              <Text>
                {(() => {
                  const dateStr = currentPost.createdAt || currentPost.publishedAt || currentPost.creator?.createdAt
                  return dateStr ? new Date(dateStr).toLocaleDateString('sr-RS') : 'N/A'
                })()}
              </Text>
            </HStack>
          </HStack>
        </VStack>

        <ImageSlider
          images={currentPost.imageUrls || (currentPost.imageUrl ? [currentPost.imageUrl] : [])}
          alt={currentPost.title}
        />

        <Divider />

        <Box
          className="blog-content"
          color={useColorModeValue('gray.700', 'gray.300')}
          dangerouslySetInnerHTML={renderHtmlContent(currentPost.description || currentPost.htmlContent || currentPost.body)}
        />

        <Divider />

        <Link href="/blog">
          <Button
            as="a"
            leftIcon={<FiArrowLeft />}
            bg={accentColor}
            color="white"
            size="lg"
            alignSelf="center"
            _hover={{ bg: '#055468' }}
          >
            Nazad na blog
          </Button>
        </Link>
      </VStack>
    </Container>
    </>
  )
}