'use client'
import {
  Container,
  Grid,
  Card,
  CardContent,
  Typography,
  Box,
  TextField,
  Button,
  Paper,
  Avatar,
  Chip,
  IconButton,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Fab,
  List,
  ListItem,
  ListItemAvatar,
  ListItemText,
  MenuItem,
  useTheme,
  CircularProgress,
  Skeleton,
} from '@mui/material'
import {
  Favorite,
  Add,
  Close,
  Person,
  AccessTime,
  FavoriteBorder,
  Share,
  MoreVert,
} from '@mui/icons-material'
import { useState, useEffect } from 'react'
import { useTranslations, useLocale, useFormatter } from 'next-intl'

interface PrayerRequest {
  id: string
  title: string
  description: string
  category: string
  author: string
  timestamp: Date
  prayerCount: number
  isPrayedFor: boolean
}

export default function PrayersPage() {
  const theme = useTheme()
  const locale = useLocale()
  const t = useTranslations('pages.prayers')
  const tc = useTranslations('common')
  const f = useFormatter()
  const [prayers, setPrayers] = useState<PrayerRequest[]>([])
  const [openDialog, setOpenDialog] = useState(false)
  const [newPrayer, setNewPrayer] = useState({
    title: '',
    description: '',
    category: 'personal',
  })
  const [loading, setLoading] = useState(true)

  const categories = [
    { value: 'personal', label: t('categories.personal'), color: 'primary' },
    { value: 'family', label: t('categories.family'), color: 'secondary' },
    { value: 'health', label: t('categories.health'), color: 'error' },
    { value: 'work', label: t('categories.work'), color: 'warning' },
    { value: 'ministry', label: t('categories.ministry'), color: 'success' },
    { value: 'world', label: t('categories.world'), color: 'info' },
  ]

  // Sample data - in real app this would come from API
  useEffect(() => {
    // Simulate loading prayers
    setTimeout(() => {
      setPrayers([
        {
          id: '1',
          title: t('samples.item1.title'),
          description: t('samples.item1.description'),
          category: 'health',
          author: t('samples.item1.author'),
          timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000),
          prayerCount: 23,
          isPrayedFor: false,
        },
        {
          id: '2',
          title: t('samples.item2.title'),
          description: t('samples.item2.description'),
          category: 'work',
          author: t('samples.item2.author'),
          timestamp: new Date(Date.now() - 5 * 60 * 60 * 1000),
          prayerCount: 15,
          isPrayedFor: true,
        },
        {
          id: '3',
          title: t('samples.item3.title'),
          description: t('samples.item3.description'),
          category: 'family',
          author: t('samples.item3.author'),
          timestamp: new Date(Date.now() - 1 * 24 * 60 * 60 * 1000),
          prayerCount: 41,
          isPrayedFor: false,
        },
      ])
      setLoading(false)
    }, 1000)
  }, [locale])

  const handleSubmitPrayer = async () => {
    if (!newPrayer.title.trim() || !newPrayer.description.trim()) return

    const prayer: PrayerRequest = {
      id: Date.now().toString(),
      title: newPrayer.title,
      description: newPrayer.description,
      category: newPrayer.category,
      author: locale === 'en' ? 'You' : 'Tu', // In real app, get from auth
      timestamp: new Date(),
      prayerCount: 0,
      isPrayedFor: false,
    }

    setPrayers([prayer, ...prayers])
    setNewPrayer({ title: '', description: '', category: 'personal' })
    setOpenDialog(false)

    // In real app, send to API
    try {
      await fetch('/api/prayers', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(prayer),
      })
    } catch (error) {
      console.error('Error submitting prayer:', error)
    }
  }

  const handlePrayFor = async (prayerId: string) => {
    setPrayers(prayers.map(prayer =>
      prayer.id === prayerId
        ? { ...prayer, prayerCount: prayer.prayerCount + 1, isPrayedFor: true }
        : prayer
    ))

    // In real app, send to API
    try {
      await fetch(`/api/prayers/${prayerId}/pray`, { method: 'POST' })
    } catch (error) {
      console.error('Error updating prayer count:', error)
    }
  }

  const getCategoryInfo = (category: string) => {
    return categories.find(cat => cat.value === category) || categories[0]
  }

  const formatTimestamp = (timestamp: Date) => {
    const now = new Date()
    const diff = now.getTime() - timestamp.getTime()
    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(minutes / 60)
    const days = Math.floor(hours / 24)

    if (days > 0) return f.relativeTime(-days, 'day')
    if (hours > 0) return f.relativeTime(-hours, 'hour')
    if (minutes > 0) return f.relativeTime(-minutes, 'minute')
    return f.relativeTime(0, 'second')
  }

  return (
    <Box>

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

        <Grid container spacing={4}>
          {/* Categories Filter */}
          <Grid item xs={12} md={3}>
            <Card>
              <CardContent>
                <Typography variant="h6" gutterBottom>
                  {t('categories.title')}
                </Typography>
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                  {categories.map((category) => (
                    <Chip
                      key={category.value}
                      label={category.label}
                      color={category.color as any}
                      variant="outlined"
                      size="small"
                      sx={{ justifyContent: 'flex-start' }}
                    />
                  ))}
                </Box>

                <Typography variant="h6" sx={{ mt: 3, mb: 1 }}>
                  {t('stats.title')}
                </Typography>
                <Typography variant="body2" color="text.secondary">
                  • {t('stats.activeRequests', { count: prayers.length })}<br />
                  • {t('stats.totalPrayers', { count: prayers.reduce((sum, p) => sum + p.prayerCount, 0) })}<br />
                  • {t('stats.youPrayed', { count: prayers.filter(p => p.isPrayedFor).length })}
                </Typography>
              </CardContent>
            </Card>
          </Grid>

          {/* Prayer Requests */}
          <Grid item xs={12} md={9}>
            {loading ? (
              <Box>
                {Array.from({ length: 3 }).map((_, index) => (
                  <Card key={index} sx={{ mb: 3 }}>
                    <CardContent>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
                        <Box sx={{ flexGrow: 1 }}>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                            <Skeleton variant="text" width="60%" height={32} />
                            <Skeleton variant="rounded" width={80} height={24} />
                          </Box>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
                            <Skeleton variant="circular" width={24} height={24} />
                            <Skeleton variant="text" width="30%" height={20} />
                          </Box>
                          <Skeleton variant="text" width="100%" height={24} />
                          <Skeleton variant="text" width="90%" height={24} />
                          <Skeleton variant="text" width="95%" height={24} />
                        </Box>
                      </Box>
                      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Box sx={{ display: 'flex', gap: 1 }}>
                          <Skeleton variant="rounded" width={100} height={32} />
                          <Skeleton variant="rounded" width={100} height={32} />
                        </Box>
                        <Skeleton variant="text" width="20%" height={20} />
                      </Box>
                    </CardContent>
                  </Card>
                ))}
              </Box>
            ) : (
              <Box>
                {prayers.map((prayer) => {
                  const categoryInfo = getCategoryInfo(prayer.category)
                  return (
                    <Card key={prayer.id} sx={{ mb: 3 }}>
                      <CardContent>
                        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', mb: 2 }}>
                          <Box sx={{ flexGrow: 1 }}>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mb: 1 }}>
                              <Typography variant="h6" component="h3">
                                {prayer.title}
                              </Typography>
                              <Chip
                                label={categoryInfo.label}
                                color={categoryInfo.color as any}
                                size="small"
                                variant="outlined"
                              />
                            </Box>

                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
                              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                                <Avatar sx={{ width: 24, height: 24, bgcolor: 'primary.main' }}>
                                  <Person sx={{ fontSize: 16 }} />
                                </Avatar>
                                <Typography variant="body2" color="text.secondary">
                                  {prayer.author}
                                </Typography>
                              </Box>
                              <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                                <AccessTime sx={{ fontSize: 16, color: 'text.secondary' }} />
                                <Typography variant="body2" color="text.secondary">
                                  {formatTimestamp(prayer.timestamp)}
                                </Typography>
                              </Box>
                            </Box>

                            <Typography variant="body1" sx={{ mb: 2 }}>
                              {prayer.description}
                            </Typography>
                          </Box>

                          <IconButton size="small">
                            <MoreVert />
                          </IconButton>
                        </Box>

                        <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                          <Box sx={{ display: 'flex', gap: 1 }}>
                            <Button
                              variant={prayer.isPrayedFor ? "contained" : "outlined"}
                              color="primary"
                              size="small"
                              startIcon={prayer.isPrayedFor ? <Favorite /> : <FavoriteBorder />}
                              onClick={() => handlePrayFor(prayer.id)}
                              disabled={prayer.isPrayedFor}
                            >
                              {prayer.isPrayedFor ? t('buttons.prayed') : t('buttons.pray')}
                            </Button>
                            <Button
                              variant="outlined"
                              size="small"
                              startIcon={<Share />}
                            >
                              {t('buttons.share')}
                            </Button>
                          </Box>

                          <Typography variant="body2" color="text.secondary">
                            {t('stats.totalPrayers', { count: prayer.prayerCount })}
                          </Typography>
                        </Box>
                      </CardContent>
                    </Card>
                  )
                })}
              </Box>
            )}
          </Grid>
        </Grid>

        {/* Add Prayer FAB */}
        <Fab
          color="primary"
          aria-label="add prayer"
          sx={{ position: 'fixed', bottom: 24, right: 24 }}
          onClick={() => setOpenDialog(true)}
        >
          <Add />
        </Fab>

        {/* Add Prayer Dialog */}
        <Dialog
          open={openDialog}
          onClose={() => setOpenDialog(false)}
          maxWidth="sm"
          fullWidth
        >
          <DialogTitle>
            <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              {t('dialog.title')}
              <IconButton onClick={() => setOpenDialog(false)} size="small">
                <Close />
              </IconButton>
            </Box>
          </DialogTitle>
          <DialogContent>
            <TextField
              fullWidth
              label={t('dialog.titleLabel')}
              value={newPrayer.title}
              onChange={(e) => setNewPrayer({ ...newPrayer, title: e.target.value })}
              sx={{ mb: 2, mt: 1 }}
            />

            <TextField
              fullWidth
              label={t('dialog.categoryLabel')}
              select
              value={newPrayer.category}
              onChange={(e) => setNewPrayer({ ...newPrayer, category: e.target.value })}
              sx={{ mb: 2 }}
            >
              {categories.map((option) => (
                <MenuItem key={option.value} value={option.value}>
                  {option.label}
                </MenuItem>
              ))}
            </TextField>

            <TextField
              fullWidth
              label={t('dialog.descriptionLabel')}
              multiline
              rows={4}
              value={newPrayer.description}
              onChange={(e) => setNewPrayer({ ...newPrayer, description: e.target.value })}
              placeholder={t('dialog.placeholder')}
            />
          </DialogContent>
          <DialogActions>
            <Button onClick={() => setOpenDialog(false)}>
              {t('dialog.cancel')}
            </Button>
            <Button
              onClick={handleSubmitPrayer}
              variant="contained"
              disabled={!newPrayer.title.trim() || !newPrayer.description.trim()}
            >
              {t('dialog.submit')}
            </Button>
          </DialogActions>
        </Dialog>
      </Container>
    </Box>
  )
}
