'use client'
import { useState, useEffect, useMemo } from 'react'
import { useT } from '@/contexts/LangContext'
import Box from '@mui/material/Box'
import Card from '@mui/material/Card'
import Typography from '@mui/material/Typography'
import TextField from '@mui/material/TextField'
import InputAdornment from '@mui/material/InputAdornment'
import Chip from '@mui/material/Chip'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableContainer from '@mui/material/TableContainer'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'
import TableSortLabel from '@mui/material/TableSortLabel'
import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'
import CircularProgress from '@mui/material/CircularProgress'
import Avatar from '@mui/material/Avatar'
import Button from '@mui/material/Button'
import Divider from '@mui/material/Divider'

// ─── Types ──────────────────────────────────────────────────────────────────

type ClientStatus = 'prospect' | 'conflict_check' | 'active' | 'closed' | 'rejected'

interface ClientFolder {
  _id: string
  folderNumber: string
  clientType: 'individual' | 'corporate'
  displayName: string
  email?: string
  phone?: string
  status: ClientStatus
  retainerBalance: number
  retainerThreshold: number
  currency: string
  responsibleAttorney: string
  originatingAttorney: string
  engagementDate?: string
  updatedAt: string
  createdAt: string
}

// ─── Config ──────────────────────────────────────────────────────────────────

const STATUS_COLORS: Record<ClientStatus, { bg: string; color: string }> = {
  active:         { bg: '#E8F7F7', color: '#0D9394' },
  prospect:       { bg: '#EEF2FF', color: '#7C6AF7' },
  conflict_check: { bg: '#FFF5DB', color: '#FFB400' },
  closed:         { bg: '#F0F0F0', color: '#6B7280' },
  rejected:       { bg: '#FFECEC', color: '#FF4C51' },
}

const FOLDER_COLORS = [
  '#4A90D9','#7B68EE','#E8533A','#2ECC71',
  '#F39C12','#0D9394','#E91E63','#FF9800',
  '#26C6DA','#8D6E63','#66BB6A','#AB47BC',
]

type SortKey = 'displayName' | 'folderNumber' | 'status' | 'retainerBalance' | 'updatedAt'
type SortDir = 'asc' | 'desc'

// ─── Helpers ─────────────────────────────────────────────────────────────────

function initials(name: string) {
  return name.split(/[\s,]+/).filter(Boolean).slice(0, 2).map(w => w[0]).join('').toUpperCase()
}

function fmtCurrency(amount: number, currency = 'THB') {
  return new Intl.NumberFormat('en-TH', { style: 'currency', currency, maximumFractionDigits: 0 }).format(amount)
}

function fmtDate(iso: string) {
  return new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' })
}

function folderColor(idx: number) {
  return FOLDER_COLORS[idx % FOLDER_COLORS.length]
}

// ─── Explorer: Folder Card ────────────────────────────────────────────────────

function FolderCard({ folder, color, selected, onSingleClick, onDoubleClick }: {
  folder: ClientFolder
  color: string
  selected: boolean
  onSingleClick: () => void
  onDoubleClick: () => void
}) {
  const st = STATUS_COLORS[folder.status]
  const lowBalance = folder.status === 'active' && folder.retainerBalance < folder.retainerThreshold

  return (
    <Box
      onClick={e => { e.stopPropagation(); onSingleClick() }}
      onDoubleClick={e => { e.stopPropagation(); onDoubleClick() }}
      sx={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 0.75,
        p: 1.5, borderRadius: 2, cursor: 'pointer', userSelect: 'none',
        border: '2px solid', transition: 'all 0.12s',
        borderColor: selected ? color : 'transparent',
        bgcolor: selected ? color + '12' : 'transparent',
        '&:hover': { bgcolor: selected ? color + '18' : 'action.hover' },
      }}
    >
      {/* Folder icon */}
      <Box sx={{ position: 'relative', width: 64, height: 54 }}>
        {/* Tab */}
        <Box sx={{ position: 'absolute', top: 0, left: 6, width: 24, height: 10,
          bgcolor: color, borderRadius: '4px 4px 0 0', opacity: 0.9 }} />
        {/* Body */}
        <Box sx={{ position: 'absolute', top: 7, left: 0, right: 0, bottom: 0,
          bgcolor: color, borderRadius: '0 4px 4px 4px', opacity: 0.85,
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 0.5 }}>
          {/* Type icon */}
          <i className={folder.clientType === 'corporate' ? 'ri-building-fill' : 'ri-user-fill'}
            style={{ fontSize: '0.85rem', color: 'rgba(255,255,255,0.75)' }} />
          {lowBalance && (
            <i className='ri-alert-fill' style={{ fontSize: '0.75rem', color: 'rgba(255,255,255,0.9)' }} />
          )}
        </Box>
        {/* Status dot */}
        <Box sx={{ position: 'absolute', bottom: -3, right: -3, width: 14, height: 14,
          borderRadius: '50%', bgcolor: st.color, border: '2px solid', borderColor: 'background.paper' }} />
      </Box>

      {/* Label */}
      <Box sx={{ textAlign: 'center', maxWidth: 110 }}>
        <Typography variant='caption' sx={{
          fontWeight: 600, lineHeight: 1.25, display: '-webkit-box',
          WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
          color: selected ? color : 'text.primary',
        }}>
          {folder.displayName}
        </Typography>
        <Typography variant='caption' sx={{ display: 'block', color: 'text.disabled', fontFamily: 'monospace', fontSize: '0.62rem', mt: 0.25 }}>
          {folder.folderNumber}
        </Typography>
      </Box>
    </Box>
  )
}

// ─── Explorer View ────────────────────────────────────────────────────────────

function ExplorerGrid({ folders, loading, lang }: {
  folders: ClientFolder[]
  loading: boolean
  lang: string
}) {
  const t = useT()
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [explorerSearch, setExplorerSearch] = useState('')

  const filteredFolders = useMemo(() => {
    const q = explorerSearch.toLowerCase().trim()
    if (!q) return folders
    return folders.filter(f =>
      f.displayName.toLowerCase().includes(q) ||
      f.folderNumber.toLowerCase().includes(q) ||
      f.email?.toLowerCase().includes(q) ||
      f.responsibleAttorney.toLowerCase().includes(q)
    )
  }, [folders, explorerSearch])

  const selectedFolder = useMemo(
    () => filteredFolders.find(f => f._id === selectedId) ?? null,
    [filteredFolders, selectedId],
  )

  const openFolder = (id: string) => { window.location.href = `/${lang}/clients/${id}` }

  if (loading) return (
    <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
      <CircularProgress size={32} />
    </Box>
  )

  return (
    <Card sx={{ overflow: 'hidden' }}>
      {/* Toolbar */}
      <Box sx={{ px: 2, py: 1.25, borderBottom: '1px solid', borderColor: 'divider',
        display: 'flex', alignItems: 'center', gap: 1.5, bgcolor: 'action.hover' }}>
        <i className='ri-folder-fill' style={{ fontSize: '1rem', color: '#0D9394' }} />
        <Typography variant='caption' sx={{ fontWeight: 600 }}>{t.clientList.folderToolbarTitle}</Typography>
        <Typography variant='caption' color='text.disabled'>{t.clientList.foldersCount(folders.length)}</Typography>
        <TextField
          size='small'
          placeholder={t.clientList.searchFolders}
          value={explorerSearch}
          onChange={e => setExplorerSearch(e.target.value)}
          sx={{ ml: 'auto', width: 220, '& .MuiInputBase-root': { fontSize: '0.8rem', height: 32 } }}
          InputProps={{
            startAdornment: <InputAdornment position='start'><i className='ri-search-line' style={{ fontSize: '0.85rem', color: '#9CA3AF' }} /></InputAdornment>,
            endAdornment: explorerSearch ? (
              <InputAdornment position='end'>
                <IconButton size='small' onClick={() => setExplorerSearch('')} sx={{ p: 0.25 }}>
                  <i className='ri-close-line' style={{ fontSize: '0.85rem' }} />
                </IconButton>
              </InputAdornment>
            ) : null,
          }}
        />
      </Box>

      {/* Grid */}
      <Box sx={{ p: 2, minHeight: 300 }} onClick={() => setSelectedId(null)}>
        {filteredFolders.length === 0 ? (
          <Box sx={{ textAlign: 'center', py: 8, color: 'text.disabled' }}>
            <i className='ri-folder-search-line' style={{ fontSize: '2.5rem' }} />
            <Typography variant='body2' sx={{ mt: 1 }}>{t.clientList.noFoldersMatch(explorerSearch)}</Typography>
          </Box>
        ) : (
          <Box sx={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(130px, 1fr))', gap: 0.5 }}>
            {filteredFolders.map((folder, i) => (
              <FolderCard
                key={folder._id}
                folder={folder}
                color={folderColor(i)}
                selected={selectedId === folder._id}
                onSingleClick={() => setSelectedId(folder._id)}
                onDoubleClick={() => openFolder(folder._id)}
              />
            ))}
          </Box>
        )}
      </Box>

      {/* Selected folder info bar */}
      {selectedFolder && (() => {
        const st = STATUS_COLORS[selectedFolder.status]
        const color = folderColor(filteredFolders.indexOf(selectedFolder))
        const lowBalance = selectedFolder.status === 'active' && selectedFolder.retainerBalance < selectedFolder.retainerThreshold
        return (
          <Box sx={{ borderTop: '1px solid', borderColor: 'divider', px: 2.5, py: 1.5,
            display: 'flex', alignItems: 'center', gap: 3, flexWrap: 'wrap' }}>
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, flex: '1 1 200px', minWidth: 0 }}>
              <Avatar sx={{ width: 34, height: 34, fontSize: '0.75rem', bgcolor: color + '22', color, fontWeight: 700 }}>
                {initials(selectedFolder.displayName)}
              </Avatar>
              <Box sx={{ minWidth: 0 }}>
                <Typography variant='body2' sx={{ fontWeight: 700, lineHeight: 1.2 }}>{selectedFolder.displayName}</Typography>
                <Typography variant='caption' color='text.disabled' sx={{ fontFamily: 'monospace' }}>{selectedFolder.folderNumber}</Typography>
              </Box>
            </Box>

            <Box sx={{ display: 'flex', gap: 2.5, alignItems: 'center', flexWrap: 'wrap' }}>
              <Chip label={t.status[selectedFolder.status === 'conflict_check' ? 'conflictCheck' : selectedFolder.status as 'active' | 'prospect' | 'closed' | 'rejected']} size='small'
                sx={{ bgcolor: st.bg, color: st.color, fontWeight: 600, fontSize: '0.65rem', height: 20 }} />

              {[
                [t.clientList.attorney, selectedFolder.responsibleAttorney],
                [t.clientList.retainer, fmtCurrency(selectedFolder.retainerBalance, selectedFolder.currency)],
                [t.clientList.updated, fmtDate(selectedFolder.updatedAt)],
              ].map(([label, val]) => (
                <Box key={label}>
                  <Typography variant='caption' color='text.disabled' sx={{ display: 'block', fontSize: '0.62rem' }}>{label}</Typography>
                  <Typography variant='caption' sx={{ fontWeight: 500,
                    color: label === 'Retainer' && lowBalance ? '#FF4C51' : 'text.primary' }}>
                    {label === 'Retainer' && lowBalance && <i className='ri-alert-line' style={{ marginRight: 3, fontSize: '0.75rem' }} />}
                    {val}
                  </Typography>
                </Box>
              ))}
            </Box>

            <Tooltip title={t.clientList.openFolder}>
              <Button size='small' variant='outlined' endIcon={<i className='ri-arrow-right-line' />}
                onClick={() => openFolder(selectedFolder._id)}
                sx={{ ml: 'auto', fontSize: '0.75rem', flexShrink: 0 }}>
                {t.common.open}
              </Button>
            </Tooltip>
          </Box>
        )
      })()}

      {/* Hint */}
      <Box sx={{ px: 2, pb: 1, borderTop: selectedFolder ? 'none' : '1px solid', borderColor: 'divider' }}>
        <Typography variant='caption' color='text.disabled' sx={{ fontSize: '0.65rem' }}>
          {t.clientList.clickHint}
        </Typography>
      </Box>
    </Card>
  )
}

// ─── Main Component ───────────────────────────────────────────────────────────

export default function ClientFolderList({ lang = 'en' }: { lang?: string }) {
  const t = useT()
  const [folders, setFolders] = useState<ClientFolder[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(true)
  const [search, setSearch] = useState('')
  const [statusFilter, setStatusFilter] = useState<ClientStatus | 'all'>('all')
  const [sortKey, setSortKey] = useState<SortKey>('updatedAt')
  const [sortDir, setSortDir] = useState<SortDir>('desc')
  const [viewMode, setViewMode] = useState<'list' | 'explorer'>('explorer')

  const STATUS_FILTERS: { label: string; value: ClientStatus | 'all' }[] = [
    { label: t.clientList.filterAll,         value: 'all' },
    { label: t.status.active,                value: 'active' },
    { label: t.status.prospect,              value: 'prospect' },
    { label: t.status.conflictCheck,         value: 'conflict_check' },
    { label: t.status.closed,                value: 'closed' },
  ]

  useEffect(() => {
    setLoading(true)
    const params = new URLSearchParams({ limit: '200' })
    if (statusFilter !== 'all') params.set('status', statusFilter)
    fetch(`/api/clients?${params}`)
      .then(r => r.json())
      .then(d => { setFolders(d.items ?? []); setTotal(d.total ?? 0) })
      .catch(() => {})
      .finally(() => setLoading(false))
  }, [statusFilter])

  const handleSort = (key: SortKey) => {
    if (sortKey === key) setSortDir(d => d === 'asc' ? 'desc' : 'asc')
    else { setSortKey(key); setSortDir('asc') }
  }

  const filtered = useMemo(() => {
    const q = search.toLowerCase().trim()
    return folders
      .filter(f => !q || f.displayName.toLowerCase().includes(q) || f.folderNumber.toLowerCase().includes(q) || f.email?.toLowerCase().includes(q))
      .sort((a, b) => {
        let av: string | number = a[sortKey] ?? ''
        let bv: string | number = b[sortKey] ?? ''
        if (sortKey === 'retainerBalance') { av = a.retainerBalance; bv = b.retainerBalance }
        const cmp = av < bv ? -1 : av > bv ? 1 : 0
        return sortDir === 'asc' ? cmp : -cmp
      })
  }, [folders, search, sortKey, sortDir])

  const lowRetainer = filtered.filter(f => f.status === 'active' && f.retainerBalance < f.retainerThreshold).length

  const col = (key: SortKey, label: string, align: 'left' | 'right' = 'left') => (
    <TableCell align={align} sx={{ fontWeight: 600, fontSize: '0.75rem', color: 'text.secondary', whiteSpace: 'nowrap' }}>
      <TableSortLabel active={sortKey === key} direction={sortKey === key ? sortDir : 'asc'} onClick={() => handleSort(key)}>
        {label}
      </TableSortLabel>
    </TableCell>
  )

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 3 }}>

      {/* Header */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <Box>
          <Typography variant='h4' sx={{ fontWeight: 600 }}>{t.clientList.title}</Typography>
          <Typography variant='body2' color='text.secondary'>
            {t.clientList.subtitle(total)}
            {lowRetainer > 0 && (
              <Box component='span' sx={{ ml: 1.5, color: '#FF4C51', fontWeight: 600 }}>
                {t.clientList.retainerAlert(lowRetainer)}
              </Box>
            )}
          </Typography>
        </Box>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
          {/* View toggle */}
          <Box sx={{ display: 'flex', border: '1px solid', borderColor: 'divider', borderRadius: 1.5, overflow: 'hidden' }}>
            <Tooltip title={t.clientList.listView}>
              <IconButton size='small' onClick={() => setViewMode('list')}
                sx={{ borderRadius: 0, px: 1.25, bgcolor: viewMode === 'list' ? '#0D939420' : 'transparent',
                  color: viewMode === 'list' ? '#0D9394' : 'text.secondary' }}>
                <i className='ri-list-check' style={{ fontSize: '1rem' }} />
              </IconButton>
            </Tooltip>
            <Divider orientation='vertical' flexItem />
            <Tooltip title={t.clientList.folderView}>
              <IconButton size='small' onClick={() => setViewMode('explorer')}
                sx={{ borderRadius: 0, px: 1.25, bgcolor: viewMode === 'explorer' ? '#0D939420' : 'transparent',
                  color: viewMode === 'explorer' ? '#0D9394' : 'text.secondary' }}>
                <i className='ri-layout-grid-line' style={{ fontSize: '1rem' }} />
              </IconButton>
            </Tooltip>
          </Box>
          <Button
            variant='contained'
            startIcon={<i className='ri-add-line' />}
            sx={{ bgcolor: '#0D9394', '&:hover': { bgcolor: '#096B6C' } }}
            href={`/${lang}/clients/new`}
          >
            {t.clientList.newClient}
          </Button>
        </Box>
      </Box>

      {/* Explorer view */}
      {viewMode === 'explorer' && (
        <ExplorerGrid folders={filtered} loading={loading} lang={lang} />
      )}

      {/* List view */}
      {viewMode === 'list' && (
        <>
          {/* Search + filters */}
          <Box sx={{ display: 'flex', gap: 2, alignItems: 'center', flexWrap: 'wrap' }}>
            <TextField
              placeholder={t.clientList.searchPlaceholder}
              size='small'
              value={search}
              onChange={e => setSearch(e.target.value)}
              sx={{ minWidth: 320 }}
              InputProps={{
                startAdornment: (
                  <InputAdornment position='start'>
                    <i className='ri-search-line' style={{ color: '#9CA3AF' }} />
                  </InputAdornment>
                ),
                endAdornment: search ? (
                  <InputAdornment position='end'>
                    <IconButton size='small' onClick={() => setSearch('')}>
                      <i className='ri-close-line' style={{ fontSize: '0.9rem' }} />
                    </IconButton>
                  </InputAdornment>
                ) : null,
              }}
            />
            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              {STATUS_FILTERS.map(f => (
                <Chip
                  key={f.value}
                  label={f.label}
                  size='small'
                  onClick={() => setStatusFilter(f.value)}
                  variant={statusFilter === f.value ? 'filled' : 'outlined'}
                  sx={statusFilter === f.value
                    ? { bgcolor: '#0D9394', color: '#fff', fontWeight: 600, border: 'none' }
                    : { cursor: 'pointer' }
                  }
                />
              ))}
            </Box>
            <Typography variant='caption' color='text.disabled' sx={{ ml: 'auto' }}>
              {filtered.length} {t.clientList.shown}
            </Typography>
          </Box>

          {/* Table */}
          <Card>
            <TableContainer>
              <Table size='small'>
                <TableHead>
                  <TableRow sx={{ '& th': { bgcolor: 'action.hover', borderBottom: '1px solid', borderColor: 'divider' } }}>
                    {col('folderNumber', t.clientList.colFolderNo)}
                    {col('displayName', t.clientList.colClient)}
                    <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem', color: 'text.secondary' }}>{t.clientList.colType}</TableCell>
                    {col('status', t.clientList.colStatus)}
                    {col('retainerBalance', t.clientList.colRetainer, 'right')}
                    <TableCell sx={{ fontWeight: 600, fontSize: '0.75rem', color: 'text.secondary' }}>{t.clientList.colAttorney}</TableCell>
                    {col('updatedAt', t.clientList.colLastUpdated)}
                    <TableCell />
                  </TableRow>
                </TableHead>
                <TableBody>
                  {loading ? (
                    <TableRow>
                      <TableCell colSpan={8} align='center' sx={{ py: 6 }}>
                        <CircularProgress size={28} />
                      </TableCell>
                    </TableRow>
                  ) : filtered.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={8} align='center' sx={{ py: 6 }}>
                        <Typography color='text.secondary'>{t.clientList.noClientsFound}</Typography>
                      </TableCell>
                    </TableRow>
                  ) : (
                    filtered.map(folder => {
                      const st = STATUS_COLORS[folder.status]
                      const lowBalance = folder.status === 'active' && folder.retainerBalance < folder.retainerThreshold
                      return (
                        <TableRow
                          key={folder._id}
                          hover
                          sx={{ cursor: 'pointer', '&:last-child td': { border: 0 } }}
                          onClick={() => window.location.href = `/${lang}/clients/${folder._id}`}
                        >
                          <TableCell>
                            <Typography variant='caption' sx={{ fontFamily: 'monospace', color: 'text.secondary' }}>
                              {folder.folderNumber}
                            </Typography>
                          </TableCell>
                          <TableCell>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
                              <Avatar sx={{ width: 30, height: 30, fontSize: '0.7rem', bgcolor: '#0D939422', color: '#0D9394', fontWeight: 700 }}>
                                {initials(folder.displayName)}
                              </Avatar>
                              <Box>
                                <Typography variant='body2' sx={{ fontWeight: 600, lineHeight: 1.2 }}>
                                  {folder.displayName}
                                </Typography>
                                {folder.email && (
                                  <Typography variant='caption' color='text.disabled'>{folder.email}</Typography>
                                )}
                              </Box>
                            </Box>
                          </TableCell>
                          <TableCell>
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.75 }}>
                              <i className={folder.clientType === 'corporate' ? 'ri-building-line' : 'ri-user-line'}
                                style={{ fontSize: '0.9rem', color: '#9CA3AF' }} />
                              <Typography variant='caption' color='text.secondary'>
                                {folder.clientType === 'corporate' ? t.clientList.corporate : t.clientList.individual}
                              </Typography>
                            </Box>
                          </TableCell>
                          <TableCell>
                            <Chip
                              label={t.status[folder.status === 'conflict_check' ? 'conflictCheck' : folder.status as 'active' | 'prospect' | 'closed' | 'rejected']}
                              size='small'
                              sx={{ bgcolor: st.bg, color: st.color, fontWeight: 600, fontSize: '0.7rem', height: 20 }}
                            />
                          </TableCell>
                          <TableCell align='right'>
                            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'flex-end', gap: 0.75 }}>
                              {lowBalance && (
                                <Tooltip title={t.clientList.belowThreshold}>
                                  <i className='ri-alert-line' style={{ fontSize: '0.9rem', color: '#FF4C51' }} />
                                </Tooltip>
                              )}
                              <Typography variant='body2' sx={{ fontWeight: lowBalance ? 700 : 400, color: lowBalance ? '#FF4C51' : 'text.primary' }}>
                                {fmtCurrency(folder.retainerBalance, folder.currency)}
                              </Typography>
                            </Box>
                          </TableCell>
                          <TableCell>
                            <Typography variant='caption' color='text.secondary'>
                              {folder.responsibleAttorney}
                            </Typography>
                          </TableCell>
                          <TableCell>
                            <Typography variant='caption' color='text.disabled'>
                              {fmtDate(folder.updatedAt)}
                            </Typography>
                          </TableCell>
                          <TableCell align='right'>
                            <Tooltip title={t.clientList.openFolder}>
                              <IconButton size='small' onClick={e => { e.stopPropagation(); window.location.href = `/${lang}/clients/${folder._id}` }}>
                                <i className='ri-arrow-right-line' style={{ fontSize: '1rem' }} />
                              </IconButton>
                            </Tooltip>
                          </TableCell>
                        </TableRow>
                      )
                    })
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </Card>
        </>
      )}
    </Box>
  )
}
