'use client'

import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import Typography from '@mui/material/Typography'
import Chip from '@mui/material/Chip'
import Divider from '@mui/material/Divider'
import Stack from '@mui/material/Stack'
import Button from '@mui/material/Button'
import CircularProgress from '@mui/material/CircularProgress'
import Box from '@mui/material/Box'
import Avatar from '@mui/material/Avatar'
import { useTranslations, useLocale } from 'next-intl'

import { useGetPaymentMethodDetails } from '@/@core/hooks/data/payment-methods'
import { getImageUrl } from '@/utils'

type Props = {
  open: boolean
  methodId?: string | null
  onClose: () => void
}

const PaymentMethodDetailsDrawer = ({ open, methodId, onClose }: Props) => {
  const t = useTranslations('paymentMethods.details')
  const rootT = useTranslations('paymentMethods')
  const locale = useLocale()

  const { data, isLoading, isError, refetch } = useGetPaymentMethodDetails(methodId || undefined, {
    enabled: open && Boolean(methodId)
  })

  const method = data?.data

  const getStatusChip = () => {
    if (!method) return null

    if (method.deleted_at) {
      return <Chip label={rootT('status.archived')} color='default' size='small' />
    }

    if (method.is_active) {
      return <Chip label={rootT('status.active')} color='success' size='small' />
    }

    return <Chip label={rootT('status.inactive')} color='warning' size='small' />
  }

  const getRequiresChip = () => {
    if (!method) return null

    return (
      <Chip
        label={method.requires_online_payment ? rootT('requires.yes') : rootT('requires.no')}
        color={method.requires_online_payment ? 'info' : 'default'}
        size='small'
      />
    )
  }

  const renderIcon = (icon?: string | null) => {
    if (!icon) {
      return <i className='tabler-credit-card' />
    }

    if (icon.startsWith('tabler')) {
      return <i className={icon} />
    }

    return <img src={getImageUrl(icon)} alt='payment-icon' className='w-full h-full object-cover' />
  }

  const renderMetaRow = (label: string, value?: string | number | string[] | null) => {
    if (Array.isArray(value)) {
      const filtered = value.filter(entry => entry && entry.trim() !== '')

      return (
        <Stack key={label} spacing={0.5}>
          <Typography color='text.secondary' variant='body2'>
            {label}
          </Typography>
          {filtered.length ? (
            <Stack spacing={0.5}>
              {filtered.map((entry, index) => (
                <Typography key={`${label}-${index}`} variant='body2' fontWeight={500}>
                  {entry}
                </Typography>
              ))}
            </Stack>
          ) : (
            <Typography variant='body2'>{t('notSet')}</Typography>
          )}
        </Stack>
      )
    }

    const hasValue = value !== undefined && value !== null && value !== ''

    return (
      <Stack direction='row' justifyContent='space-between' gap={2} key={label}>
        <Typography color='text.secondary' variant='body2'>
          {label}
        </Typography>
        <Typography variant='body1' fontWeight={500} textAlign='right'>
          {hasValue ? value : t('notSet')}
        </Typography>
      </Stack>
    )
  }

  const renderContent = () => {
    if (isLoading) {
      return (
        <div className='flex items-center justify-center py-10'>
          <CircularProgress />
        </div>
      )
    }

    if (isError) {
      return (
        <Stack spacing={2} className='py-10'>
          <Typography color='error'>{rootT('list.error')}</Typography>
          <Button variant='contained' onClick={() => refetch()}>
            {rootT('list.retry')}
          </Button>
        </Stack>
      )
    }

    if (!method) {
      return (
        <Typography color='text.secondary' className='py-6'>
          {rootT('list.empty')}
        </Typography>
      )
    }

    const localizedName = locale === 'ar' ? method.name_ar : method.name_en
    const secondaryName = locale === 'ar' ? method.name_en : method.name_ar

    return (
      <Stack spacing={4}>
        <Box
          className='rounded-2xl p-4 text-white'
          sx={{
            background: 'linear-gradient(135deg, var(--mui-palette-primary-main), #4e65ff)'
          }}
        >
          <Stack direction='row' spacing={3} alignItems='center'>
            <Avatar
              sx={{
                width: 64,
                height: 64,
                bgcolor: 'rgba(255,255,255,0.2)',
                border: '1px solid rgba(255,255,255,0.4)'
              }}
            >
              {renderIcon(method.icon)}
            </Avatar>
            <Stack spacing={0.5} flex={1}>
              <Typography variant='h6'>{localizedName}</Typography>
              <Typography variant='body2' color='rgba(255,255,255,0.8)'>
                {secondaryName}
              </Typography>
              <Stack direction='row' spacing={1} flexWrap='wrap'>
                <Chip
                  size='small'
                  label={method.type === 'online' ? rootT('types.online') : rootT('types.offline')}
                  color={method.type === 'online' ? 'primary' : 'secondary'}
                  sx={{ bgcolor: 'rgba(255,255,255,0.2)', color: '#fff' }}
                />
                {getStatusChip()}
                {getRequiresChip()}
              </Stack>
            </Stack>
          </Stack>

          <Stack direction={{ xs: 'column', sm: 'row' }} spacing={3} mt={3}>
            <Stack>
              <Typography variant='caption' color='rgba(255,255,255,0.7)'>
                {rootT('card.code')}
              </Typography>
              <Typography variant='body1'>{method.code}</Typography>
            </Stack>
            <Stack>
              <Typography variant='caption' color='rgba(255,255,255,0.7)'>
                {rootT('card.sortOrder')}
              </Typography>
              <Typography variant='body1'>{method.sort_order ?? '—'}</Typography>
            </Stack>
            <Stack>
              <Typography variant='caption' color='rgba(255,255,255,0.7)'>
                {rootT('card.fees')}
              </Typography>
              <Typography variant='body1'>
                {method.fee_percentage || 0}% · {method.fee_fixed || 0}
              </Typography>
            </Stack>
          </Stack>
        </Box>

        <Box>
          <Typography variant='subtitle2' gutterBottom>
            {t('overview')}
          </Typography>
          <Stack spacing={2}>
            <div>
              <Typography variant='caption' color='text.secondary'>
                {t('descriptionEn')}
              </Typography>
              <Typography variant='body1' fontWeight={500}>
                {method.description_en || t('notSet')}
              </Typography>
            </div>
            <div>
              <Typography variant='caption' color='text.secondary'>
                {t('descriptionAr')}
              </Typography>
              <Typography variant='body1' fontWeight={500}>
                {method.description_ar || t('notSet')}
              </Typography>
            </div>
          </Stack>
        </Box>

        <Box>
          <Typography variant='subtitle2' gutterBottom>
            {t('instructions')}
          </Typography>
          <Stack spacing={2}>
            <div>
              <Typography variant='caption' color='text.secondary'>
                {t('instructionsEn')}
              </Typography>
              <Typography variant='body1' fontWeight={500}>
                {method.instructions_en || t('notSet')}
              </Typography>
            </div>
            <div>
              <Typography variant='caption' color='text.secondary'>
                {t('instructionsAr')}
              </Typography>
              <Typography variant='body1' fontWeight={500}>
                {method.instructions_ar || t('notSet')}
              </Typography>
            </div>
          </Stack>
        </Box>

        <Box>
          <Typography variant='subtitle2' gutterBottom>
            {t('fees')}
          </Typography>
          <Stack spacing={1}>
            {renderMetaRow(rootT('card.percentage'), method.fee_percentage || '0')}
            {renderMetaRow(rootT('card.fixedFee'), method.fee_fixed || '0')}
          </Stack>
        </Box>

        <Box>
          <Typography variant='subtitle2' gutterBottom>
            {t('banking')}
          </Typography>
          <Stack spacing={1}>
            {renderMetaRow(rootT('form.bankName'), method.bank_name)}
            {renderMetaRow(rootT('form.accountHolder'), method.account_holder)}
            {renderMetaRow(rootT('form.accountNumber'), method.account_number)}
            {renderMetaRow(rootT('form.iban'), method.iban)}
            {renderMetaRow(rootT('form.swift'), method.swift_code)}
          </Stack>
        </Box>

        <Box>
          <Typography variant='subtitle2' gutterBottom>
            {t('wallet')}
          </Typography>
          <Stack spacing={1}>
            {renderMetaRow(rootT('form.walletHolder'), method.wallet_holder)}
            {renderMetaRow(rootT('form.walletNumber'), method.wallet_number)}
          </Stack>
        </Box>

        <Box>
          <Typography variant='subtitle2' gutterBottom>
            {t('gateway')}
          </Typography>
          <Stack spacing={1}>
            {renderMetaRow(rootT('form.gatewayUrl'), method.gateway_url)}
            {renderMetaRow(rootT('form.gatewayConfig'), method.gateway_config)}
          </Stack>
        </Box>

        <Box>
          <Typography variant='subtitle2' gutterBottom>
            {t('metadata')}
          </Typography>
          <Stack spacing={1}>
            {renderMetaRow(rootT('card.code'), method.code)}
            {renderMetaRow(rootT('card.sortOrder'), method.sort_order)}
            {renderMetaRow(t('recordId'), method.id)}
            {renderMetaRow(t('modelId'), method.entity_model_id)}
          </Stack>
        </Box>

        <Box>
          <Typography variant='subtitle2' gutterBottom>
            {t('created')}
          </Typography>
          <Typography variant='body2'>
            {method.created_at ? new Date(method.created_at).toLocaleString(locale) : t('notSet')}
          </Typography>
          <Typography variant='subtitle2' gutterBottom className='mt-3'>
            {t('updated')}
          </Typography>
          <Typography variant='body2'>
            {method.updated_at ? new Date(method.updated_at).toLocaleString(locale) : t('notSet')}
          </Typography>
        </Box>
      </Stack>
    )
  }

  return (
    <Drawer
      anchor='right'
      open={open}
      onClose={onClose}
      sx={{ '& .MuiDrawer-paper': { width: { xs: 360, sm: 480 }, p: 4 } }}
    >
      <div className='flex items-center justify-between mb-3'>
        <Typography variant='h6'>{t('title')}</Typography>
        <IconButton onClick={onClose}>
          <i className='tabler-x text-textSecondary' />
        </IconButton>
      </div>
      <Divider sx={{ mb: 4 }} />
      {renderContent()}
      <Divider sx={{ mt: 4, mb: 2 }} />
      <Button onClick={onClose} variant='contained'>
        {t('close')}
      </Button>
    </Drawer>
  )
}

export default PaymentMethodDetailsDrawer
