'use client'
import {
  Container,
  Grid,
  Card,
  CardContent,
  Typography,
  Box,
  Select,
  MenuItem,
  FormControl,
  InputLabel,
  Paper,
  List,
  ListItem,
  ListItemButton,
  ListItemText,
  Divider,
  Button,
  Chip,
  useTheme,
  CircularProgress,
  Skeleton,
} from '@mui/material'
import {
  MenuBook,
  NavigateBefore,
  NavigateNext,
  Bookmark,
  Share,
} from '@mui/icons-material'
import { useState, useEffect } from 'react'
import { useTranslations, useLocale } from 'next-intl'

interface BibleVerse {
  id: string
  verseNum: number
  text: string
}

interface BibleChapter {
  id: string
  chapterNum: number
  verses: BibleVerse[]
}

interface BibleBook {
  id: string
  name: string
  testament: string
  orderNum: number
  bookKey: string
  chapters: BibleChapter[]
}

export default function BiblePage() {
  const theme = useTheme()
  const t = useTranslations('pages.bible')
  const locale = useLocale()
  const [books, setBooks] = useState<BibleBook[]>([])
  const [selectedBook, setSelectedBook] = useState<string>('')
  const [selectedChapter, setSelectedChapter] = useState<number>(1)
  const [verses, setVerses] = useState<BibleVerse[]>([])
  const [loading, setLoading] = useState(true)

  // Fetch available books
  useEffect(() => {
    fetch(`/api/bible/books?locale=${locale}`)
      .then(res => res.json())
      .then(data => {
        setBooks(data.books || [])
        if (data.books && data.books.length > 0) {
          setSelectedBook(data.books[0].id)
        }
        setLoading(false)
      })
      .catch(err => {
        console.error('Error fetching books:', err)
        setLoading(false)
      })
  }, [])

  // Fetch verses when book/chapter changes
  useEffect(() => {
    if (selectedBook && selectedChapter) {
      setLoading(true)
      fetch(`/api/bible/verses?bookId=${selectedBook}&chapter=${selectedChapter}`)
        .then(res => res.json())
        .then(data => {
          setVerses(data.verses || [])
          setLoading(false)
        })
        .catch(err => {
          console.error('Error fetching verses:', err)
          setLoading(false)
        })
    }
  }, [selectedBook, selectedChapter])

  const currentBook = books.find(book => book.id === selectedBook)
  const maxChapters = currentBook?.chapters?.length || 50 // Default fallback

  const handlePreviousChapter = () => {
    if (selectedChapter > 1) {
      setSelectedChapter(selectedChapter - 1)
    } else if (selectedBook > 1) {
      setSelectedBook(selectedBook - 1)
      setSelectedChapter(50) // Will be adjusted by actual chapter count
    }
  }

  const handleNextChapter = () => {
    if (selectedChapter < maxChapters) {
      setSelectedChapter(selectedChapter + 1)
    } else {
      const nextBook = books.find(book => book.id === selectedBook + 1)
      if (nextBook) {
        setSelectedBook(selectedBook + 1)
        setSelectedChapter(1)
      }
    }
  }

  if (loading && books.length === 0) {
    return (
      <Box>
        <Container maxWidth="lg" sx={{ py: 4 }}>
          <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2 }}>
            <CircularProgress size={48} />
            <Typography variant="h6" color="text.secondary">
              {t('loading')}
            </Typography>
          </Box>
        </Container>
      </Box>
    )
  }

  return (
    <Box>

      <Container maxWidth="lg" sx={{ py: 4 }}>
        {/* Header */}
        <Box sx={{ mb: 4, textAlign: 'center' }}>
          <Typography variant="h3" component="h1" gutterBottom>
            <MenuBook sx={{ fontSize: 40, mr: 2, verticalAlign: 'middle' }} />
            {t('title')}
          </Typography>
          <Typography variant="body1" color="text.secondary">
            {t('subtitle')}
          </Typography>
        </Box>

        <Grid container spacing={4}>
          {/* Left Sidebar - Book Selection */}
          <Grid item xs={12} md={3}>
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  {t('selectBook')}
                </Typography>

                <FormControl fullWidth sx={{ mb: 2 }}>
                  <InputLabel>{t('book')}</InputLabel>
                  <Select
                    value={selectedBook}
                    label={t('book')}
                    onChange={(e) => {
                      setSelectedBook(e.target.value)
                      setSelectedChapter(1)
                    }}
                  >
                    {books.map((book) => (
                      <MenuItem key={book.id} value={book.id}>
                        {book.name}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>

                <FormControl fullWidth>
                  <InputLabel>{t('chapter')}</InputLabel>
                  <Select
                    value={selectedChapter}
                    label={t('chapter')}
                    onChange={(e) => setSelectedChapter(Number(e.target.value))}
                  >
                    {Array.from({ length: maxChapters }, (_, i) => (
                      <MenuItem key={i + 1} value={i + 1}>
                        {t('chapter')} {i + 1}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>

                <Box sx={{ mt: 2, display: 'flex', gap: 1 }}>
                  <Chip
                    label={currentBook?.testament || 'Vechiul Testament'}
                    size="small"
                    color="primary"
                    variant="outlined"
                  />
                </Box>
              </CardContent>
            </Card>
          </Grid>

          {/* Main Content - Bible Text */}
          <Grid item xs={12} md={9}>
            <Card>
              <CardContent>
                {/* Chapter Header */}
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
                  <Box>
                    <Typography variant="h4" component="h2">
                      {currentBook?.name || 'Geneza'} {selectedChapter}
                    </Typography>
                    <Typography variant="body2" color="text.secondary">
                      {verses.length} {t('verses')}
                    </Typography>
                  </Box>

                  <Box sx={{ display: 'flex', gap: 1 }}>
                    <Button
                      startIcon={<Bookmark />}
                      variant="outlined"
                      size="small"
                    >
                      {t('save')}
                    </Button>
                    <Button
                      startIcon={<Share />}
                      variant="outlined"
                      size="small"
                    >
                      {t('share')}
                    </Button>
                  </Box>
                </Box>

                <Divider sx={{ mb: 3 }} />

                {/* Bible Verses */}
                {loading ? (
                  <Box>
                    {Array.from({ length: 5 }).map((_, index) => (
                      <Box key={index} sx={{ mb: 2 }}>
                        <Skeleton variant="text" width="100%" height={40} />
                        <Skeleton variant="text" width="90%" height={30} />
                        <Skeleton variant="text" width="95%" height={30} />
                      </Box>
                    ))}
                  </Box>
                ) : verses.length > 0 ? (
                  <Box>
                    {verses.map((verse) => (
                      <Box key={verse.id} sx={{ mb: 2 }}>
                        <Typography
                          variant="body1"
                          component="p"
                          sx={{
                            lineHeight: 1.8,
                            fontSize: '1.1rem',
                            '&:hover': {
                              bgcolor: 'action.hover',
                              cursor: 'pointer',
                              borderRadius: 1,
                              p: 1,
                              m: -1,
                            },
                          }}
                        >
                          <Typography
                            component="span"
                            sx={{
                              fontWeight: 'bold',
                              color: 'primary.main',
                              mr: 1,
                              fontSize: '0.9rem',
                            }}
                          >
                            {verse.verseNum}
                          </Typography>
                          {verse.text}
                        </Typography>
                      </Box>
                    ))}
                  </Box>
                ) : (
                  <Typography textAlign="center" color="text.secondary">
                    {t('noVerses')}
                  </Typography>
                )}

                {/* Navigation */}
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mt: 4, pt: 3, borderTop: 1, borderColor: 'divider' }}>
                  <Button
                    startIcon={<NavigateBefore />}
                    onClick={handlePreviousChapter}
                    disabled={selectedBook === 1 && selectedChapter === 1}
                  >
                    {t('previousChapter')}
                  </Button>

                  <Typography variant="body2" color="text.secondary" sx={{ alignSelf: 'center' }}>
                    {currentBook?.name} {selectedChapter}
                  </Typography>

                  <Button
                    endIcon={<NavigateNext />}
                    onClick={handleNextChapter}
                    disabled={selectedBook === books.length && selectedChapter === maxChapters}
                  >
                    {t('nextChapter')}
                  </Button>
                </Box>
              </CardContent>
            </Card>
          </Grid>
        </Grid>
      </Container>
    </Box>
  )
}