'use client'

import Link from 'next/link'
import { useParams } from 'next/navigation'
import { useLocale, useTranslations } from 'next-intl'
import Card from '@mui/material/Card'
import CardHeader from '@mui/material/CardHeader'
import CardContent from '@mui/material/CardContent'
import Typography from '@mui/material/Typography'
import Grid from '@mui/material/Grid2'
import Box from '@mui/material/Box'
import Stack from '@mui/material/Stack'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import Divider from '@mui/material/Divider'
import Skeleton from '@mui/material/Skeleton'
import LinearProgress from '@mui/material/LinearProgress'
import type { ChipProps } from '@mui/material/Chip'

import themeConfig from '@configs/themeConfig'
import { useGetOrdersStatistics } from '@/@core/hooks/data/orders'
import type { ORDER_STATUS, ORDER_TYPE } from '@/types/data'

const orderTypes: ORDER_TYPE[] = ['dine_in', 'takeaway', 'delivery']
const statusOrder: ORDER_STATUS[] = [
  'pending',
  'confirmed',
  'preparing',
  'ready',
  'delivered',
  'completed',
  'cancelled'
]

const typeColorMap: Record<ORDER_TYPE, ChipProps['color']> = {
  dine_in: 'primary',
  takeaway: 'secondary',
  delivery: 'info'
}

const statusColorMap: Record<ORDER_STATUS, ChipProps['color']> = {
  pending: 'warning',
  confirmed: 'info',
  preparing: 'info',
  ready: 'success',
  delivered: 'success',
  completed: 'secondary',
  cancelled: 'error'
}

const DashboardHomePage = () => {
  const t = useTranslations('dashboard.home')
  const locale = useLocale()
  const params = useParams()
  const lang = (params?.lang as string) || locale || 'en'
  const productName = themeConfig.templateName || 'Menu'

  const { data: statsResponse, isLoading: statsLoading } = useGetOrdersStatistics({})
  const stats = statsResponse?.data
  const localeFormatter = locale === 'ar' ? 'ar-SA' : 'en-US'
  const currencyCode = t('stats.currencyCode') || 'SAR'

  const formatNumber = (value: number | string | null | undefined, options?: Intl.NumberFormatOptions): string => {
    if (value === undefined || value === null) return '�'
    const numeric = Number(value)
    if (Number.isNaN(numeric)) return '�'
    return new Intl.NumberFormat(localeFormatter, options).format(numeric)
  }

  const formatCurrency = (value: number | string | null | undefined) =>
    formatNumber(value, {
      style: 'currency',
      currency: currencyCode,
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    })

  const heroInsights = ['tables', 'orders', 'categories', 'products'].map(item => t(`heroInsights.${item}`))

  const statsCards: Array<{
    key: string
    label: string
    helper: string
    value: number | string | null | undefined
    format: 'number' | 'currency'
  }> = [
    {
      key: 'todayOrders',
      label: t('stats.todayOrders'),
      helper: t('stats.todayOrdersHint'),
      value: stats?.today?.total_orders,
      format: 'number'
    },
    {
      key: 'todayRevenue',
      label: t('stats.todayRevenue'),
      helper: t('stats.todayRevenueHint'),
      value: stats?.today?.revenue,
      format: 'currency'
    },
    {
      key: 'pending',
      label: t('stats.pending'),
      helper: t('stats.pendingHint'),
      value: stats?.today?.pending_orders,
      format: 'number'
    },
    {
      key: 'monthOrders',
      label: t('stats.monthOrders'),
      helper: t('stats.monthOrdersHint'),
      value: stats?.this_month?.total_orders,
      format: 'number'
    },
    {
      key: 'monthRevenue',
      label: t('stats.monthRevenue'),
      helper: t('stats.monthRevenueHint'),
      value: stats?.this_month?.revenue,
      format: 'currency'
    }
  ]

  const typeBreakdown = orderTypes.map(type => ({
    key: type,
    label: t(`stats.byType.${type}`),
    value: stats?.by_type?.[type] ?? 0,
    color: typeColorMap[type]
  }))

  const totalTypes = typeBreakdown.reduce((sum, type) => sum + (Number(type.value) || 0), 0)

  return (
    <Box className='p-6 space-y-6'>
      <Grid container spacing={4}>
        <Grid size={{ xs: 12 }}>
          <Card
            sx={{
              background: 'linear-gradient(135deg, #181F3B 0%, #3A7BD5 100%)',
              color: 'common.white',
              position: 'relative',
              overflow: 'hidden'
            }}
          >
            <CardContent>
              <Grid container spacing={4} alignItems='center'>
                <Grid size={{ xs: 12, md: 8 }}>
                  <Stack spacing={2}>
                    <Typography variant='h4' fontWeight={600}>
                      {t('welcome')}{' '}
                      <Box component='span' sx={{ color: 'primary.light' }}>
                        {productName}
                      </Box>{' '}
                    </Typography>
                    <Typography sx={{ color: 'rgba(255,255,255,0.85)' }}>{t('heroSubtitle')}</Typography>
                    <Stack direction='row' spacing={1} flexWrap='wrap'>
                      {heroInsights.map(text => (
                        <Chip
                          key={text}
                          label={text}
                          size='small'
                          sx={{ backgroundColor: 'rgba(255,255,255,0.2)', color: 'common.white' }}
                        />
                      ))}
                    </Stack>
                    <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} mt={2}>
                      <Button component={Link} href={`/${lang}/orders`} variant='contained' color='secondary'>
                        {t('heroPrimaryCta')}
                      </Button>
                      <Button component={Link} href={`/${lang}/tables`} variant='text' color='inherit'>
                        {t('heroSecondaryCta')}
                      </Button>
                    </Stack>
                  </Stack>
                </Grid>
                <Grid size={{ xs: 12, md: 4 }}>
                  <Stack spacing={1} textAlign={{ xs: 'start', md: 'end' }}>
                    {statsLoading ? (
                      <Skeleton variant='text' height={56} sx={{ bgcolor: 'rgba(255,255,255,0.2)' }} />
                    ) : (
                      <Typography variant='h2'>{formatNumber(stats?.today?.total_orders)}</Typography>
                    )}
                    <Typography sx={{ color: 'rgba(255,255,255,0.7)' }}>{t('heroMetricSubtitle')}</Typography>
                  </Stack>
                </Grid>
              </Grid>
            </CardContent>
          </Card>
        </Grid>
      </Grid>

      <Grid container spacing={4}>
        <Grid size={{ xs: 12 }}>
          <Grid container spacing={4}>
            {statsCards?.map(card => (
              <Grid size={{ xs: 12, sm: 6, md: 4 }} key={card.key}>
                <Card variant='outlined' sx={{ height: '100%' }}>
                  <CardContent>
                    <Stack spacing={1.5}>
                      <Typography color='text.secondary'>{card.label}</Typography>
                      {statsLoading ? (
                        <Skeleton variant='text' width='60%' height={38} />
                      ) : (
                        <Typography variant='h4'>
                          {card.format === 'currency' ? formatCurrency(card.value) : formatNumber(card.value)}
                        </Typography>
                      )}
                      <Typography variant='body2' color='text.disabled'>
                        {card.helper}
                      </Typography>
                    </Stack>
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
        </Grid>
      </Grid>

      <Grid container spacing={4}>
        <Grid size={{ xs: 12, lg: 6 }}>
          <Card variant='outlined'>
            <CardHeader title={t('stats.byTypeTitle')} subheader={t('stats.byTypeSubtitle')} />
            <CardContent>
              <Stack spacing={2}>
                {typeBreakdown.map(type => (
                  <Box key={type.key}>
                    <Stack direction='row' justifyContent='space-between' alignItems='center'>
                      <Typography>{type.label}</Typography>
                      {statsLoading ? (
                        <Skeleton width={40} height={24} />
                      ) : (
                        <Typography fontWeight={600}>{formatNumber(type.value)}</Typography>
                      )}
                    </Stack>
                    <LinearProgress
                      variant='determinate'
                      value={totalTypes ? (Number(type.value) / totalTypes) * 100 : 0}
                      sx={{ height: 8, borderRadius: 999, mt: 1 }}
                    />
                  </Box>
                ))}
                {!statsLoading && totalTypes === 0 && (
                  <Typography variant='body2' color='text.disabled'>
                    {t('stats.empty')}
                  </Typography>
                )}
              </Stack>
            </CardContent>
          </Card>
        </Grid>
        <Grid size={{ xs: 12, lg: 6 }}>
          <Card variant='outlined'>
            <CardHeader title={t('stats.byStatusTitle')} subheader={t('stats.byStatusSubtitle')} />
            <CardContent>
              <Stack divider={<Divider flexItem />}>
                {statusOrder.map(status => (
                  <Stack
                    key={status}
                    direction='row'
                    alignItems='center'
                    justifyContent='space-between'
                    py={1.5}
                    gap={2}
                  >
                    <Chip
                      label={t(`stats.byStatus.${status}`)}
                      size='small'
                      color={statusColorMap[status]}
                      variant='outlined'
                    />
                    {statsLoading ? (
                      <Skeleton width={40} height={24} />
                    ) : (
                      <Typography fontWeight={600}>{formatNumber(stats?.by_status?.[status] ?? 0)}</Typography>
                    )}
                  </Stack>
                ))}
              </Stack>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  )
}

export default DashboardHomePage
