'use client'

import { useCallback, useEffect, useMemo, useState } from 'react'
import Grid from '@mui/material/Grid2'
import Card from '@mui/material/Card'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Chip from '@mui/material/Chip'
import CustomTextField from '@core/components/mui/TextField'
import MenuItem from '@mui/material/MenuItem'
import Stack from '@mui/material/Stack'
import FormControlLabel from '@mui/material/FormControlLabel'
import Switch from '@mui/material/Switch'
import Divider from '@mui/material/Divider'
import CircularProgress from '@mui/material/CircularProgress'
import Avatar from '@mui/material/Avatar'
import Pagination from '@mui/material/Pagination'
import Tooltip from '@mui/material/Tooltip'
import Dialog from '@mui/material/Dialog'
import DialogTitle from '@mui/material/DialogTitle'
import DialogContent from '@mui/material/DialogContent'
import DialogActions from '@mui/material/DialogActions'
import { useTheme } from '@mui/material/styles'
import { useLocale, useTranslations } from 'next-intl'
import { useRouter, useSearchParams } from 'next/navigation'
import { toast } from 'react-toastify'

import {
  useGetPaymentMethodsList,
  useTogglePaymentMethod,
  useDeletePaymentMethod,
  useRestorePaymentMethod
} from '@/@core/hooks/data/payment-methods'
import { IPaymentMethodDetails } from '@/types/data/payment-method'
import PaymentMethodFormDrawer from './PaymentMethodFormDrawer'
import PaymentMethodDetailsDrawer from './PaymentMethodDetailsDrawer'
import { getImageUrl } from '@/utils'

type SortField = 'sort_order' | 'code' | 'name_en' | 'created_at'

const PaymentMethodsView = () => {
  const t = useTranslations('paymentMethods')
  const formT = useTranslations('paymentMethods.form')
  const messageT = useTranslations('paymentMethods.messages')
  const locale = useLocale()
  const theme = useTheme()
  const router = useRouter()
  const searchParams = useSearchParams()

  const [searchValue, setSearchValue] = useState(searchParams.get('search') || '')
  const [formState, setFormState] = useState<{ open: boolean; mode: 'create' | 'edit'; methodId?: string | null }>({
    open: false,
    mode: 'create',
    methodId: null
  })
  const [detailsId, setDetailsId] = useState<string | null>(null)
  const [confirmDialog, setConfirmDialog] = useState<{
    action: 'delete' | 'restore'
    method?: IPaymentMethodDetails | null
  }>({ action: 'delete', method: null })
  const [toggleTarget, setToggleTarget] = useState<string | null>(null)

  const page = Number(searchParams.get('page') || 1)
  const perPage = Number(searchParams.get('per_page') || 6)
  const typeParam = (searchParams.get('type') as 'online' | 'offline' | null) || null
  const typeFilter: 'all' | 'online' | 'offline' = typeParam || 'all'
  const statusParam = searchParams.get('is_active')
  const statusFilter: 'all' | 'active' | 'inactive' =
    statusParam === '1' ? 'active' : statusParam === '0' ? 'inactive' : 'all'
  const requiresParam = searchParams.get('requires_online_payment')
  const requiresFilter: 'all' | 'yes' | 'no' = requiresParam === '1' ? 'yes' : requiresParam === '0' ? 'no' : 'all'
  const sortBy = (searchParams.get('sort_by') as SortField) || 'sort_order'
  const sortDirection = (searchParams.get('sort_as') as 'asc' | 'desc') || 'asc'
  const searchTerm = searchParams.get('search')?.trim() || ''

  useEffect(() => {
    setSearchValue(searchParams.get('search') || '')
  }, [searchParams])

  const applyFilters = useCallback(
    (updates: Record<string, string | number | undefined>) => {
      const params = new URLSearchParams(searchParams.toString())

      Object.entries(updates).forEach(([key, value]) => {
        if (value === undefined || value === null || value === '' || value === 'undefined') {
          params.delete(key)
        } else {
          params.set(key, String(value))
        }
      })

      const query = params.toString()
      router.replace(query ? `?${query}` : '?', { scroll: false })
    },
    [router, searchParams]
  )

  useEffect(() => {
    if (searchValue === searchTerm) {
      return
    }

    const handler = setTimeout(() => {
      const trimmed = searchValue.trim()
      applyFilters({
        search: trimmed || undefined,
        page: 1
      })
    }, 500)

    return () => clearTimeout(handler)
  }, [searchValue, searchTerm, applyFilters])

  const query = useMemo(
    () => ({
      page,
      per_page: perPage,
      search: searchTerm || undefined,
      type: typeFilter !== 'all' ? typeFilter : undefined,
      is_active: statusFilter === 'all' ? undefined : statusFilter === 'active' ? 1 : 0,
      requires_online_payment: requiresFilter === 'all' ? undefined : requiresFilter === 'yes' ? 1 : 0,
      sort_by: sortBy,
      sort_as: sortDirection
    }),
    [page, perPage, searchTerm, typeFilter, statusFilter, requiresFilter, sortBy, sortDirection]
  )

  const { data, isLoading, isFetching, error, refetch } = useGetPaymentMethodsList(query)

  const methods: IPaymentMethodDetails[] = data?.data?.data || []
  const total = data?.data?.total || 0
  const pageCount = Math.max(1, Math.ceil(total / perPage))

  const stats = useMemo(() => {
    const visibleMethods = methods.filter(method => !method.deleted_at)
    const active = visibleMethods.filter(method => method.is_active).length
    const online = visibleMethods.filter(method => method.type === 'online').length
    const offline = visibleMethods.filter(method => method.type === 'offline').length
    const requireOnline = methods.filter(method => method.requires_online_payment).length
    const awaitingActivation = visibleMethods.filter(method => !method.is_active).length
    const avgFee =
      methods.length > 0
        ? methods.reduce((sum, method) => sum + (parseFloat(String(method.fee_percentage || 0)) || 0), 0) /
          methods.length
        : 0

    return {
      total: methods.length,
      active,
      online,
      offline,
      requireOnline,
      awaitingActivation,
      avgFee
    }
  }, [methods])

  const toggleMutation = useTogglePaymentMethod()
  const deleteMutation = useDeletePaymentMethod()
  const restoreMutation = useRestorePaymentMethod()

  const handleToggle = async (method: IPaymentMethodDetails) => {
    if (method.deleted_at) return
    setToggleTarget(method.id)
    try {
      const response = await toggleMutation.mutateAsync(method.id)
      toast.success(response?.messages || messageT('toggled'))
    } catch (err) {
      console.error('Failed to toggle payment method', err)
      toast.error(messageT('error'))
    } finally {
      setToggleTarget(null)
    }
  }

  const handleConfirmAction = async () => {
    if (!confirmDialog.method) return

    try {
      if (confirmDialog.action === 'delete') {
        const response = await deleteMutation.mutateAsync(confirmDialog.method.id)
        toast.success(response?.messages || messageT('deleted'))
      } else {
        const response = await restoreMutation.mutateAsync(confirmDialog.method.id)
        toast.success(response?.messages || messageT('restored'))
      }
      setConfirmDialog({ action: 'delete', method: null })
    } catch (err) {
      console.error('Failed to update payment method archive state', err)
      toast.error(messageT('error'))
    }
  }

  const handleResetFilters = () => {
    setSearchValue('')
    applyFilters({
      search: undefined,
      page: 1,
      per_page: 6,
      type: undefined,
      is_active: undefined,
      requires_online_payment: undefined,
      sort_by: 'sort_order',
      sort_as: 'asc',
      with_deleted: undefined
    })
  }

  const renderStatsCard = (
    label: string,
    value: string | number,
    icon: string,
    color: 'primary' | 'success' | 'info' | 'warning' | 'secondary' | 'error'
  ) => (
    <Card variant='outlined' className='p-4 h-full flex flex-col gap-2'>
      <Stack direction='row' justifyContent='space-between' alignItems='center'>
        <Typography variant='body2' color='text.secondary'>
          {label}
        </Typography>
        <Avatar
          sx={{
            bgcolor: `var(--mui-palette-${color}-light)`,
            color: `var(--mui-palette-${color}-main)`,
            width: 40,
            height: 40
          }}
        >
          <i className={icon} />
        </Avatar>
      </Stack>
      <Typography variant='h5'>{value}</Typography>
    </Card>
  )

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

    if (icon.startsWith('tabler')) {
      return <i className={`${icon} text-lg text-primary.main`} />
    }

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

  const localizedName = (method: IPaymentMethodDetails) => (locale === 'ar' ? method.name_ar : method.name_en)
  const secondaryName = (method: IPaymentMethodDetails) => (locale === 'ar' ? method.name_en : method.name_ar)
  const localizedDescription = (method: IPaymentMethodDetails) =>
    (locale === 'ar' ? method.description_ar : method.description_en) ||
    (locale === 'ar' ? method.description_en : method.description_ar) ||
    ''

  const showingCount = t('showingCount', { count: methods.length })
  const heroGradient = 'linear-gradient(135deg, var(--mui-palette-primary-main), #2c3e50)'
  const insightCardStyles = {
    background: 'linear-gradient(135deg, rgba(255,255,255,0.18), rgba(255,255,255,0.06))',
    color: '#fff',
    border: '1px solid rgba(255,255,255,0.25)'
  }

  const typeChipOptions = [
    { value: 'all', icon: 'tabler-category', label: t('types.all'), tooltip: t('chipHints.type_all') },
    { value: 'online', icon: 'tabler-world', label: t('types.online'), tooltip: t('chipHints.type_online') },
    { value: 'offline', icon: 'tabler-building-store', label: t('types.offline'), tooltip: t('chipHints.type_offline') }
  ]
  const statusChipOptions = [
    { value: 'all', icon: 'tabler-circle-check', label: t('status.all'), tooltip: t('chipHints.status_all') },
    { value: 'active', icon: 'tabler-bolt', label: t('status.active'), tooltip: t('chipHints.status_active') },
    { value: 'inactive', icon: 'tabler-moon', label: t('status.inactive'), tooltip: t('chipHints.status_inactive') }
  ]

  return (
    <Grid container spacing={6}>
      <Grid size={{ xs: 12, lg: 8 }}>
        <Stack spacing={4}>
          <Card className='p-6 text-white' sx={{ background: heroGradient, color: '#fff' }}>
            <Stack direction={{ xs: 'column', md: 'row' }} spacing={3} justifyContent='space-between'>
              <div>
                <Typography variant='h5'>{t('title')}</Typography>
                <Typography variant='body2' color='rgba(255,255,255,0.7)'>
                  {t('subtitle')}
                </Typography>
              </div>
              <Stack direction='row' spacing={2} alignItems='center'>
                <div className='text-center'>
                  <Typography variant='body2' color='rgba(255,255,255,0.7)'>
                    {t('stats.total')}
                  </Typography>
                  <Typography variant='h4'>{stats.total}</Typography>
                </div>
                <div className='text-center'>
                  <Typography variant='body2' color='rgba(255,255,255,0.7)'>
                    {t('stats.active')}
                  </Typography>
                  <Typography variant='h4'>{stats.active}</Typography>
                </div>
                <Button
                  variant='contained'
                  color='secondary'
                  onClick={() => setFormState({ open: true, mode: 'create', methodId: null })}
                >
                  <i className='tabler-plus mr-1' />
                  {t('addMethod')}
                </Button>
              </Stack>
            </Stack>

            <Divider sx={{ my: 4, borderColor: 'rgba(255,255,255,0.2)' }} />

            <Stack direction={{ xs: 'column', md: 'row' }} spacing={3}>
              <Stack spacing={1} flex={1}>
                <Typography variant='caption' color='rgba(255,255,255,0.7)'>
                  {t('filters.type')}
                </Typography>
                <Stack direction='row' spacing={1} flexWrap='wrap'>
                  {typeChipOptions?.map(filter => (
                    <Tooltip key={filter.value} title={filter.tooltip}>
                      <Chip
                        icon={<i className={`${filter.icon} text-white`} />}
                        label={filter.label}
                        color={typeFilter === filter.value ? 'secondary' : 'default'}
                        variant={typeFilter === filter.value ? 'filled' : 'outlined'}
                        onClick={() =>
                          applyFilters({
                            type: filter.value === 'all' ? undefined : filter.value,
                            page: 1
                          })
                        }
                        sx={{ color: typeFilter === filter.value ? '#fff' : 'inherit' }}
                      />
                    </Tooltip>
                  ))}
                </Stack>
              </Stack>
              <Stack spacing={1} flex={1}>
                <Typography variant='caption' color='rgba(255,255,255,0.7)'>
                  {t('filters.status')}
                </Typography>
                <Stack direction='row' spacing={1} flexWrap='wrap'>
                  {statusChipOptions?.map(filter => (
                    <Tooltip key={filter.value} title={filter.tooltip}>
                      <Chip
                        icon={<i className={`${filter.icon} text-white`} />}
                        label={filter.label}
                        color={statusFilter === filter.value ? 'secondary' : 'default'}
                        variant={statusFilter === filter.value ? 'filled' : 'outlined'}
                        onClick={() =>
                          applyFilters({
                            is_active: filter.value === 'all' ? undefined : filter.value === 'active' ? 1 : 0,
                            page: 1
                          })
                        }
                        sx={{ color: statusFilter === filter.value ? '#fff' : 'inherit' }}
                      />
                    </Tooltip>
                  ))}
                </Stack>
              </Stack>
            </Stack>

            <Stack direction={{ xs: 'column', md: 'row' }} spacing={3} mt={4}>
              <Card className='p-4 flex-1' elevation={0} sx={insightCardStyles}>
                <Typography variant='body2' color='#fff'>
                  {t('insights.activeOnline')}
                </Typography>
                <Typography variant='h5' color='#fff'>
                  {stats.online}
                </Typography>
              </Card>
              <Card className='p-4 flex-1' elevation={0} sx={insightCardStyles}>
                <Typography variant='body2' color='#fff'>
                  {t('insights.offlineReady')}
                </Typography>
                <Typography variant='h5' color='#fff'>
                  {stats.offline}
                </Typography>
              </Card>
              <Card className='p-4 flex-1' elevation={0} sx={insightCardStyles}>
                <Typography variant='body2' color='#fff'>
                  {t('insights.awaitingActivation')}
                </Typography>
                <Typography variant='h5' color='#fff'>
                  {stats.awaitingActivation}
                </Typography>
              </Card>
              <Card className='p-4 flex-1' elevation={0} sx={insightCardStyles}>
                <Typography variant='body2' color='#fff'>
                  {t('insights.avgFee')}
                </Typography>
                <Typography variant='h5' color='#fff'>
                  {stats.avgFee.toFixed(1)}%
                </Typography>
              </Card>
            </Stack>
          </Card>

          <Card className='p-6 space-y-4'>
            <Stack direction={{ xs: 'column', sm: 'row' }} justifyContent='space-between' spacing={2}>
              <div>
                <Typography variant='h6'>{t('title')}</Typography>
                <Typography variant='body2' color='text.secondary'>
                  {t('subtitle')}
                </Typography>
              </div>
              <Button variant='outlined' onClick={() => setFormState({ open: true, mode: 'create', methodId: null })}>
                <i className='tabler-plus mr-1' />
                {t('addMethod')}
              </Button>
            </Stack>

            <Stack direction={{ xs: 'column', md: 'row' }} spacing={3} alignItems={'flex-end'}>
              <CustomTextField
                placeholder={t('searchPlaceholder')}
                value={searchValue}
                onChange={event => setSearchValue(event.target.value)}
                className='flex-1'
              />
              <CustomTextField
                select
                label={t('filters.type')}
                value={typeFilter}
                onChange={event =>
                  applyFilters({
                    type: event.target.value === 'all' ? undefined : event.target.value,
                    page: 1
                  })
                }
                className='min-w-[160px]'
              >
                <MenuItem value='all'>{t('types.all')}</MenuItem>
                <MenuItem value='online'>{t('types.online')}</MenuItem>
                <MenuItem value='offline'>{t('types.offline')}</MenuItem>
              </CustomTextField>
              <CustomTextField
                select
                label={t('filters.status')}
                value={statusFilter}
                onChange={event =>
                  applyFilters({
                    is_active: event.target.value === 'all' ? undefined : event.target.value === 'active' ? 1 : 0,
                    page: 1
                  })
                }
                className='min-w-[160px]'
              >
                <MenuItem value='all'>{t('status.all')}</MenuItem>
                <MenuItem value='active'>{t('status.active')}</MenuItem>
                <MenuItem value='inactive'>{t('status.inactive')}</MenuItem>
              </CustomTextField>
              <CustomTextField
                select
                label={t('filters.requiresOnline')}
                value={requiresFilter}
                onChange={event =>
                  applyFilters({
                    requires_online_payment:
                      event.target.value === 'all' ? undefined : event.target.value === 'yes' ? 1 : 0,
                    page: 1
                  })
                }
                className='min-w-[160px]'
              >
                <MenuItem value='all'>{t('requires.all')}</MenuItem>
                <MenuItem value='yes'>{t('requires.yes')}</MenuItem>
                <MenuItem value='no'>{t('requires.no')}</MenuItem>
              </CustomTextField>
            </Stack>

            <Stack direction={{ xs: 'column', md: 'row' }} spacing={3}>
              <CustomTextField
                select
                label={t('filters.sortBy')}
                value={sortBy}
                onChange={event =>
                  applyFilters({
                    sort_by: event.target.value,
                    page: 1
                  })
                }
                className='min-w-[160px]'
              >
                <MenuItem value='sort_order'>{t('sort.sort_order')}</MenuItem>
                <MenuItem value='code'>{t('sort.code')}</MenuItem>
                <MenuItem value='name_en'>{t('sort.name_en')}</MenuItem>
                <MenuItem value='created_at'>{t('sort.created_at')}</MenuItem>
              </CustomTextField>
              <CustomTextField
                select
                label={t('filters.sortDirection')}
                value={sortDirection}
                onChange={event =>
                  applyFilters({
                    sort_as: event.target.value,
                    page: 1
                  })
                }
                className='min-w-[160px]'
              >
                <MenuItem value='asc'>{t('sort.asc')}</MenuItem>
                <MenuItem value='desc'>{t('sort.desc')}</MenuItem>
              </CustomTextField>
              <CustomTextField
                select
                label='Per page'
                value={perPage}
                onChange={event =>
                  applyFilters({
                    per_page: Number(event.target.value),
                    page: 1
                  })
                }
                className='min-w-[140px]'
              >
                <MenuItem value={6}>6</MenuItem>
                <MenuItem value={12}>12</MenuItem>
                <MenuItem value={24}>24</MenuItem>
              </CustomTextField>
            </Stack>

            <Stack direction='row' flexWrap='wrap' spacing={2} justifyContent={'space-between'} alignItems='center'>
              <Button variant='tonal' color='secondary' onClick={handleResetFilters}>
                {t('filters.reset')}
              </Button>
              <Chip label={showingCount} />
              <Button variant='text' onClick={() => refetch()}>
                <i className='tabler-refresh mr-1' />
                {t('refresh')}
              </Button>
              {isFetching && <CircularProgress size={20} />}
            </Stack>
          </Card>
        </Stack>
      </Grid>

      <Grid size={{ xs: 12, lg: 4 }}>
        <Grid container spacing={3}>
          <Grid size={{ xs: 12, sm: 6, lg: 12 }}>
            {renderStatsCard(t('stats.total'), stats.total, 'tabler-credit-card', 'primary')}
          </Grid>
          <Grid size={{ xs: 12, sm: 6, lg: 6 }}>
            {renderStatsCard(t('stats.active'), stats.active, 'tabler-check', 'success')}
          </Grid>
          <Grid size={{ xs: 12, sm: 6, lg: 6 }}>
            {renderStatsCard(t('stats.online'), stats.online, 'tabler-world', 'info')}
          </Grid>
          <Grid size={{ xs: 12, sm: 6, lg: 6 }}>
            {renderStatsCard(t('stats.offline'), stats.offline, 'tabler-building-store', 'warning')}
          </Grid>
          <Grid size={{ xs: 12, sm: 6, lg: 6 }}>
            {renderStatsCard(t('stats.requiresOnline'), stats.requireOnline, 'tabler-shield-lock', 'secondary')}
          </Grid>
          <Grid size={{ xs: 12, sm: 6, lg: 12 }}>
            {renderStatsCard(t('stats.fees'), `${stats.avgFee.toFixed(1)}%`, 'tabler-percentage', 'error')}
          </Grid>
        </Grid>
      </Grid>

      <Grid size={12}>
        <Card className='p-6 space-y-4'>
          {error ? (
            <Stack spacing={2} alignItems='center' className='py-10'>
              <Typography color='error'>{t('list.error')}</Typography>
              <Button variant='contained' onClick={() => refetch()}>
                {t('list.retry')}
              </Button>
            </Stack>
          ) : isLoading ? (
            <Grid container spacing={3}>
              {Array.from({ length: perPage }).map((_, index) => (
                <Grid key={`pm-skeleton-${index}`} size={{ xs: 12, md: 6, xl: 4 }}>
                  <Card className='p-4 space-y-3 animate-pulse'>
                    <div className='h-6 bg-gray-200 rounded' />
                    <div className='h-4 bg-gray-100 rounded' />
                    <div className='h-4 bg-gray-100 rounded w-3/4' />
                    <div className='h-4 bg-gray-100 rounded w-2/3' />
                  </Card>
                </Grid>
              ))}
            </Grid>
          ) : methods.length === 0 ? (
            <div className='py-16 text-center'>
              <Typography color='text.secondary'>{t('list.empty')}</Typography>
            </div>
          ) : (
            <>
              <Grid container spacing={3}>
                {methods.map(method => {
                  const inactive = !method.is_active || Boolean(method.deleted_at)
                  const isToggling = toggleMutation.isPending && toggleTarget === method.id
                  const statusLabel = method.deleted_at
                    ? t('status.archived')
                    : method.is_active
                      ? t('status.active')
                      : t('status.inactive')

                  return (
                    <Grid key={method.id} size={{ xs: 12, md: 6, xl: 4 }}>
                      <Card className='p-4 h-full flex flex-col gap-4 hover:shadow-lg transition-shadow duration-300'>
                        <Stack direction='row' alignItems='center' justifyContent='space-between' spacing={2}>
                          <Stack direction='row' spacing={2} alignItems='center'>
                            <Avatar variant='rounded' sx={{ width: 48, height: 48, bgcolor: 'primary.light' }}>
                              {renderIcon(method.icon)}
                            </Avatar>
                            <div>
                              <Typography fontWeight={600}>{localizedName(method)}</Typography>
                              <Typography variant='body2' color='text.secondary'>
                                {secondaryName(method)}
                              </Typography>
                            </div>
                          </Stack>
                          <div className='text-right'>
                            <Chip
                              label={statusLabel}
                              size='small'
                              color={method.deleted_at ? 'default' : method.is_active ? 'success' : 'warning'}
                            />
                          </div>
                        </Stack>

                        <Typography
                          variant='body1'
                          color='text.primary'
                          className='line-clamp-2'
                          sx={{ fontWeight: 500 }}
                        >
                          {localizedDescription(method)}
                        </Typography>

                        <Stack direction='row' spacing={1} flexWrap='wrap'>
                          <Chip
                            label={method.type === 'online' ? t('types.online') : t('types.offline')}
                            size='small'
                            color={method.type === 'online' ? 'primary' : 'secondary'}
                          />
                          <Chip
                            label={
                              method.requires_online_payment ? t('card.requiresOnline') : t('card.collectedOffline')
                            }
                            size='small'
                            color={method.requires_online_payment ? 'info' : 'default'}
                          />
                        </Stack>

                        <Stack direction='row' spacing={2} alignItems='center' justifyContent='space-between'>
                          <div>
                            <Typography variant='caption' color='text.secondary'>
                              {t('card.fees')}
                            </Typography>
                            <Typography variant='body2'>
                              {method.fee_percentage || 0}% · {method.fee_fixed || 0}
                            </Typography>
                          </div>
                          <Stack direction='row' spacing={1} alignItems='center'>
                            <FormControlLabel
                              control={
                                <Switch
                                  checked={Boolean(method.is_active) && !method.deleted_at}
                                  onChange={() => handleToggle(method)}
                                  disabled={Boolean(method.deleted_at) || isToggling}
                                  size='small'
                                />
                              }
                              label={method.is_active && !method.deleted_at ? t('status.active') : t('status.inactive')}
                            />
                            {isToggling && <CircularProgress size={16} />}
                          </Stack>
                        </Stack>

                        <Divider />

                        <Stack direction='row' spacing={1} flexWrap='wrap'>
                          <Button
                            size='small'
                            variant='outlined'
                            onClick={() => setDetailsId(method.id)}
                            startIcon={<i className='tabler-eye' />}
                          >
                            {t('actions.view')}
                          </Button>
                          <Button
                            size='small'
                            variant='outlined'
                            color='secondary'
                            onClick={() => setFormState({ open: true, mode: 'edit', methodId: method.id })}
                            startIcon={<i className='tabler-edit' />}
                          >
                            {t('actions.edit')}
                          </Button>
                          {method.deleted_at ? (
                            <Button
                              size='small'
                              variant='contained'
                              color='success'
                              onClick={() => setConfirmDialog({ action: 'restore', method })}
                              startIcon={<i className='tabler-rotate-2' />}
                            >
                              {t('actions.restore')}
                            </Button>
                          ) : (
                            <Button
                              size='small'
                              variant='outlined'
                              color='error'
                              onClick={() => setConfirmDialog({ action: 'delete', method })}
                              startIcon={<i className='tabler-archive' />}
                            >
                              {t('actions.delete')}
                            </Button>
                          )}
                        </Stack>

                        <Stack direction='row' justifyContent='space-between' alignItems='center'>
                          <Typography variant='caption' color='text.secondary'>
                            {t('card.lastUpdated')}
                          </Typography>
                          <Typography variant='caption'>
                            {method.updated_at ? new Date(method.updated_at).toLocaleString(locale) : '—'}
                          </Typography>
                        </Stack>
                      </Card>
                    </Grid>
                  )
                })}
              </Grid>

              <Divider />

              <Stack direction={{ xs: 'column', md: 'row' }} justifyContent='space-between' alignItems='center'>
                <Typography variant='body2' color='text.secondary'>
                  {showingCount}
                </Typography>
                <Pagination
                  page={page}
                  count={pageCount}
                  onChange={(_, value) => applyFilters({ page: value })}
                  color='primary'
                />
              </Stack>
            </>
          )}
        </Card>
      </Grid>

      <PaymentMethodFormDrawer
        open={formState.open}
        mode={formState.mode}
        methodId={formState.methodId}
        onClose={() => setFormState({ open: false, mode: 'create', methodId: null })}
        onSuccess={() => refetch()}
      />

      <PaymentMethodDetailsDrawer open={Boolean(detailsId)} methodId={detailsId} onClose={() => setDetailsId(null)} />

      <Dialog
        open={Boolean(confirmDialog.method)}
        onClose={() => setConfirmDialog({ action: 'delete', method: null })}
        maxWidth='xs'
        fullWidth
      >
        <DialogTitle>
          {confirmDialog.action === 'delete' ? t('actions.confirmDeleteTitle') : t('actions.confirmRestoreTitle')}
        </DialogTitle>
        <DialogContent>
          <Typography variant='body2'>
            {confirmDialog.action === 'delete'
              ? t('actions.confirmDeleteMessage', {
                  name: confirmDialog.method ? localizedName(confirmDialog.method) : ''
                })
              : t('actions.confirmRestoreMessage', {
                  name: confirmDialog.method ? localizedName(confirmDialog.method) : ''
                })}
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button
            onClick={() => setConfirmDialog({ action: 'delete', method: null })}
            disabled={deleteMutation.isPending || restoreMutation.isPending}
          >
            {formT('cancel')}
          </Button>
          <Button
            onClick={handleConfirmAction}
            variant='contained'
            color={confirmDialog.action === 'delete' ? 'error' : 'success'}
            disabled={deleteMutation.isPending || restoreMutation.isPending}
            startIcon={
              deleteMutation.isPending || restoreMutation.isPending ? (
                <CircularProgress size={16} color='inherit' />
              ) : confirmDialog.action === 'delete' ? (
                <i className='tabler-archive' />
              ) : (
                <i className='tabler-rotate-2' />
              )
            }
          >
            {confirmDialog.action === 'delete' ? t('actions.delete') : t('actions.restore')}
          </Button>
        </DialogActions>
      </Dialog>
    </Grid>
  )
}

export default PaymentMethodsView
