// ** React Imports
// import { useState, useEffect } from 'react'

// // ** MUI Components
// import Button from '@mui/material/Button'
// import Typography from '@mui/material/Typography'
// import Box from '@mui/material/Box'
// import TextField from '@mui/material/TextField'
// import MenuItem from '@mui/material/MenuItem'
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import CardContent from '@mui/material/CardContent'
// import Paper from '@mui/material/Paper'
// import InputAdornment from '@mui/material/InputAdornment'
// 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 CircularProgress from '@mui/material/CircularProgress'
// import Alert from '@mui/material/Alert'
// import IconButton from '@mui/material/IconButton'
// import Tooltip from '@mui/material/Tooltip'
// import { styled, useTheme } from '@mui/material/styles'

// // ** Icons
// import Icon from 'src/@core/components/icon'

// // ** Third Party Imports
// import { useForm, Controller } from 'react-hook-form'

// // Currency list with exchange rates (base: USD)
// const currencies = [
//   { code: 'USD', name: 'US Dollar', symbol: '$', rate: 1.0000, flag: '🇺🇸' },
//   { code: 'EUR', name: 'Euro', symbol: '€', rate: 0.9200, flag: '🇪🇺' },
//   { code: 'GBP', name: 'British Pound', symbol: '£', rate: 0.7900, flag: '🇬🇧' },
//   { code: 'JPY', name: 'Japanese Yen', symbol: '¥', rate: 154.3200, flag: '🇯🇵' },
//   { code: 'CAD', name: 'Canadian Dollar', symbol: 'C$', rate: 1.3700, flag: '🇨🇦' },
//   { code: 'AUD', name: 'Australian Dollar', symbol: 'A$', rate: 1.5200, flag: '🇦🇺' },
//   { code: 'CHF', name: 'Swiss Franc', symbol: 'Fr', rate: 0.9100, flag: '🇨🇭' },
//   { code: 'CNY', name: 'Chinese Yuan', symbol: '¥', rate: 7.2400, flag: '🇨🇳' },
//   { code: 'INR', name: 'Indian Rupee', symbol: '₹', rate: 83.4500, flag: '🇮🇳' },
//   { code: 'SGD', name: 'Singapore Dollar', symbol: 'S$', rate: 1.3500, flag: '🇸🇬' },
//   { code: 'NZD', name: 'New Zealand Dollar', symbol: 'NZ$', rate: 1.6700, flag: '🇳🇿' },
//   { code: 'MXN', name: 'Mexican Peso', symbol: '$', rate: 17.0500, flag: '🇲🇽' },
//   { code: 'BRL', name: 'Brazilian Real', symbol: 'R$', rate: 5.1200, flag: '🇧🇷' },
//   { code: 'ZAR', name: 'South African Rand', symbol: 'R', rate: 18.7500, flag: '🇿🇦' },
//   { code: 'AED', name: 'UAE Dirham', symbol: 'د.إ', rate: 3.6700, flag: '🇦🇪' },
//   { code: 'SAR', name: 'Saudi Riyal', symbol: '﷼', rate: 3.7500, flag: '🇸🇦' },
//   { code: 'TRY', name: 'Turkish Lira', symbol: '₺', rate: 32.1500, flag: '🇹🇷' },
//   { code: 'KRW', name: 'South Korean Won', symbol: '₩', rate: 1375.5000, flag: '🇰🇷' },
//   { code: 'RUB', name: 'Russian Ruble', symbol: '₽', rate: 91.2500, flag: '🇷🇺' },
//   { code: 'HKD', name: 'Hong Kong Dollar', symbol: 'HK$', rate: 7.8200, flag: '🇭🇰' }
// ]

// interface FormValues {
//   amount: number
//   fromCurrency: string
//   toCurrency: string
// }

// const FXManager = () => {
//   const theme = useTheme()
//   const [exchangedAmount, setExchangedAmount] = useState<number>(0)
//   const [exchangeRate, setExchangeRate] = useState<number>(1)
//   const [loading, setLoading] = useState<boolean>(false)

//   const {
//     control,
//     watch,
//     setValue,
//     getValues,
//     formState: { errors }
//   } = useForm<FormValues>({
//     defaultValues: {
//       amount: 0,
//       fromCurrency: 'USD',
//       toCurrency: 'EUR'
//     }
//   })

//   const amount = watch('amount')
//   const fromCurrency = watch('fromCurrency')
//   const toCurrency = watch('toCurrency')

//   // Get exchange rate between two currencies
//   const getExchangeRate = (from: string, to: string): number => {
//     const fromRate = currencies.find(c => c.code === from)?.rate || 1
//     const toRate = currencies.find(c => c.code === to)?.rate || 1
//     return toRate / fromRate
//   }

//   // Calculate exchanged amount
//   const calculateExchange = () => {
//     if (!amount || amount <= 0) return
//     setLoading(true)
//     setTimeout(() => {
//       const rate = getExchangeRate(fromCurrency, toCurrency)
//       setExchangeRate(rate)
//       const result = amount * rate
//       setExchangedAmount(result)
//       setLoading(false)
//     }, 300)
//   }

//   // Update exchange rate when currencies change
//   useEffect(() => {
//     if (amount > 0) {
//       calculateExchange()
//     } else {
//       setExchangeRate(getExchangeRate(fromCurrency, toCurrency))
//       setExchangedAmount(0)
//     }
//   }, [fromCurrency, toCurrency])

//   // Handle amount change
//   useEffect(() => {
//     if (amount > 0 && amount !== undefined) {
//       calculateExchange()
//     } else {
//       setExchangedAmount(0)
//     }
//   }, [amount])

//   // Swap currencies
//   const handleSwapCurrencies = () => {
//     const currentFrom = getValues('fromCurrency')
//     const currentTo = getValues('toCurrency')
//     setValue('fromCurrency', currentTo)
//     setValue('toCurrency', currentFrom)
//   }

//   // Format currency
//   const formatCurrency = (value: number, currencyCode: string) => {
//     return new Intl.NumberFormat('en-US', {
//       style: 'currency',
//       currency: currencyCode,
//       minimumFractionDigits: 2,
//       maximumFractionDigits: 2
//     }).format(value)
//   }

//   // Get currency symbol
//   const getCurrencySymbol = (currencyCode: string) => {
//     return currencies.find(c => c.code === currencyCode)?.symbol || '$'
//   }

//   return (
//     <Box sx={{ p: 6 }}>
//       <Grid container spacing={6}>
//         {/* Header Section */}
//         <Grid item xs={12}>
//           <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
//             <Box>
//               <Typography variant='h4' sx={{ fontWeight: 700, mb: 1 }}>
//                 Current FX Balance
//               </Typography>
//               <Typography variant='body2' sx={{ color: 'text.secondary' }}>
//                 Manage your foreign exchange conversions with real-time exchange rates
//               </Typography>
//             </Box>
//             <Tooltip title='Refresh Rates'>
//               <IconButton onClick={calculateExchange} sx={{ bgcolor: 'action.hover' }}>
//                 <Icon icon='ri:refresh-line' fontSize={24} />
//               </IconButton>
//             </Tooltip>
//           </Box>
//         </Grid>

//         {/* Exchange Rate Table Section */}
//         <Grid item xs={12} md={6}>
//           <Card sx={{ height: '100%' }}>
//             <CardContent>
//               <Typography variant='h6' sx={{ mb: 3, color: 'primary.main', fontWeight: 600 }}>
//                 Currency Exchange Rates
//               </Typography>
//               <TableContainer sx={{ maxHeight: 500 }}>
//                 <Table stickyHeader size='small'>
//                   <TableHead>
//                     <TableRow>
//                       <TableCell><Typography fontWeight='bold'>Currency</Typography></TableCell>
//                       <TableCell align='right'><Typography fontWeight='bold'>Rate (vs USD)</Typography></TableCell>
//                     </TableRow>
//                   </TableHead>
//                   <TableBody>
//                     {currencies.map((currency) => (
//                       <TableRow key={currency.code} hover>
//                         <TableCell>
//                           <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
//                             <Typography fontSize={20}>{currency.flag}</Typography>
//                             <Typography fontWeight={600}>{currency.code}</Typography>
//                             <Typography variant='body2' color='text.secondary'>{currency.name}</Typography>
//                           </Box>
//                         </TableCell>
//                         <TableCell align='right'>
//                           <Typography fontWeight={500}>
//                             {currency.symbol} {currency.rate.toFixed(4)}
//                           </Typography>
//                         </TableCell>
//                       </TableRow>
//                     ))}
//                   </TableBody>
//                 </Table>
//               </TableContainer>
//             </CardContent>
//           </Card>
//         </Grid>

//         {/* Currency Converter Section */}
//         <Grid item xs={12} md={6}>
//           <Card sx={{ height: '100%' }}>
//             <CardContent>
//               <Typography variant='h6' sx={{ mb: 3, color: 'primary.main', fontWeight: 600 }}>
//                 Currency Converter
//               </Typography>

//               <Box sx={{ mb: 4 }}>
//                 <Controller
//                   name='amount'
//                   control={control}
//                   rules={{ 
//                     required: 'Amount is required',
//                     min: { value: 0.01, message: 'Amount must be greater than 0' }
//                   }}
//                   render={({ field }) => (
//                     <TextField
//                       {...field}
//                       fullWidth
//                       type='number'
//                       label='Amount'
//                       placeholder='Enter amount'
//                       error={!!errors.amount}
//                       helperText={errors.amount?.message}
//                       InputProps={{
//                         startAdornment: <InputAdornment position='start'>{getCurrencySymbol(fromCurrency)}</InputAdornment>
//                       }}
//                     />
//                   )}
//                 />
//               </Box>

//               <Grid container spacing={2} alignItems='center'>
//                 <Grid item xs={12} sm={5}>
//                   <Controller
//                     name='fromCurrency'
//                     control={control}
//                     render={({ field }) => (
//                       <TextField
//                         {...field}
//                         select
//                         fullWidth
//                         label='Convert From'
//                         size='small'
//                       >
//                         {currencies.map((currency) => (
//                           <MenuItem key={currency.code} value={currency.code}>
//                             <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
//                               <Typography>{currency.flag}</Typography>
//                               <Typography fontWeight={500}>{currency.code}</Typography>
//                               <Typography variant='caption' color='text.secondary'>{currency.name}</Typography>
//                             </Box>
//                           </MenuItem>
//                         ))}
//                       </TextField>
//                     )}
//                   />
//                 </Grid>

//                 <Grid item xs={12} sm={2} sx={{ textAlign: 'center' }}>
//                   <IconButton 
//                     onClick={handleSwapCurrencies} 
//                     sx={{ 
//                       bgcolor: 'primary.main', 
//                       color: 'white',
//                       '&:hover': { bgcolor: 'primary.dark' }
//                     }}
//                   >
//                     <Icon icon='ri:swap-line' fontSize={20} />
//                   </IconButton>
//                 </Grid>

//                 <Grid item xs={12} sm={5}>
//                   <Controller
//                     name='toCurrency'
//                     control={control}
//                     render={({ field }) => (
//                       <TextField
//                         {...field}
//                         select
//                         fullWidth
//                         label='Convert To'
//                         size='small'
//                       >
//                         {currencies.map((currency) => (
//                           <MenuItem key={currency.code} value={currency.code}>
//                             <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
//                               <Typography>{currency.flag}</Typography>
//                               <Typography fontWeight={500}>{currency.code}</Typography>
//                               <Typography variant='caption' color='text.secondary'>{currency.name}</Typography>
//                             </Box>
//                           </MenuItem>
//                         ))}
//                       </TextField>
//                     )}
//                   />
//                 </Grid>
//               </Grid>

//               {/* Exchange Rate Display */}
//               <Alert severity='info' sx={{ my: 3 }}>
//                 <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
//                   <Typography variant='body2'>Exchange Rate</Typography>
//                   <Typography variant='h6' fontWeight={600}>
//                     1 {fromCurrency} = {exchangeRate.toFixed(4)} {toCurrency}
//                   </Typography>
//                 </Box>
//               </Alert>

//               {/* Exchanged Amount */}
//               <Paper sx={{ 
//                 p: 4, 
//                 bgcolor: 'primary.main', 
//                 color: 'white', 
//                 textAlign: 'center',
//                 borderRadius: 2,
//                 mb: 3
//               }}>
//                 <Typography variant='body2' sx={{ mb: 1, opacity: 0.9, textTransform: 'uppercase', letterSpacing: 1 }}>
//                   Exchanged Amount
//                 </Typography>
//                 {loading ? (
//                   <CircularProgress size={40} color='inherit' />
//                 ) : (
//                   <Typography variant='h2' sx={{ fontWeight: 700 }}>
//                     {amount > 0 ? formatCurrency(exchangedAmount, toCurrency) : `${getCurrencySymbol(toCurrency)} 0.00`}
//                   </Typography>
//                 )}
//               </Paper>

//               {/* Convert Button */}
//               <Button
//                 fullWidth
//                 size='large'
//                 variant='contained'
//                 onClick={calculateExchange}
//                 disabled={!amount || amount <= 0 || loading}
//                 sx={{ py: 1.5 }}
//               >
//                 {loading ? <CircularProgress size={24} color='inherit' /> : 'Convert Currency'}
//               </Button>

//               {/* Info Text */}
//               <Typography variant='caption' sx={{ mt: 2, display: 'block', textAlign: 'center', color: 'text.secondary' }}>
//                 Exchange rates are updated in real-time. Rates shown are for informational purposes only.
//               </Typography>
//             </CardContent>
//           </Card>
//         </Grid>
//       </Grid>
//     </Box>
//   )
// }

// FXManager.acl = {
//   action: 'read',
//   subject: 'user-management'
// }


// export default FXManager

// new changes 
import { useState, useEffect, useCallback, useMemo } from 'react'

// ** MUI Components
import Button from '@mui/material/Button'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'
import TextField from '@mui/material/TextField'
import MenuItem from '@mui/material/MenuItem'
import Grid from '@mui/material/Grid'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import Paper from '@mui/material/Paper'
import InputAdornment from '@mui/material/InputAdornment'
import CircularProgress from '@mui/material/CircularProgress'
import Alert from '@mui/material/Alert'
import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'
import Chip from '@mui/material/Chip'
import Divider from '@mui/material/Divider'
import Fade from '@mui/material/Fade'
import Zoom from '@mui/material/Zoom'
import { styled, useTheme, alpha } from '@mui/material/styles'
import useMediaQuery from '@mui/material/useMediaQuery'

// ** Data Grid Imports
import { DataGrid, GridColDef, GridRowParams, GridCellParams } from '@mui/x-data-grid'

// ** Icons
import Icon from 'src/@core/components/icon'

// ** Third Party Imports
import { useForm, Controller } from 'react-hook-form'

// Currency list with exchange rates (base: USD)
const currencies = [
  { code: 'USD', name: 'US Dollar', symbol: '$', rate: 1.0000, flag: '🇺🇸' },
  { code: 'EUR', name: 'Euro', symbol: '€', rate: 0.9200, flag: '🇪🇺' },
  { code: 'GBP', name: 'British Pound', symbol: '£', rate: 0.7900, flag: '🇬🇧' },
  { code: 'JPY', name: 'Japanese Yen', symbol: '¥', rate: 154.3200, flag: '🇯🇵' },
  { code: 'CAD', name: 'Canadian Dollar', symbol: 'C$', rate: 1.3700, flag: '🇨🇦' },
  { code: 'AUD', name: 'Australian Dollar', symbol: 'A$', rate: 1.5200, flag: '🇦🇺' },
  { code: 'CHF', name: 'Swiss Franc', symbol: 'Fr', rate: 0.9100, flag: '🇨🇭' },
  { code: 'CNY', name: 'Chinese Yuan', symbol: '¥', rate: 7.2400, flag: '🇨🇳' },
  { code: 'INR', name: 'Indian Rupee', symbol: '₹', rate: 83.4500, flag: '🇮🇳' },
  { code: 'SGD', name: 'Singapore Dollar', symbol: 'S$', rate: 1.3500, flag: '🇸🇬' },
  { code: 'NZD', name: 'New Zealand Dollar', symbol: 'NZ$', rate: 1.6700, flag: '🇳🇿' },
  { code: 'MXN', name: 'Mexican Peso', symbol: '$', rate: 17.0500, flag: '🇲🇽' },
  { code: 'BRL', name: 'Brazilian Real', symbol: 'R$', rate: 5.1200, flag: '🇧🇷' },
  { code: 'ZAR', name: 'South African Rand', symbol: 'R', rate: 18.7500, flag: '🇿🇦' },
  { code: 'AED', name: 'UAE Dirham', symbol: 'د.إ', rate: 3.6700, flag: '🇦🇪' },
  { code: 'SAR', name: 'Saudi Riyal', symbol: '﷼', rate: 3.7500, flag: '🇸🇦' },
  { code: 'TRY', name: 'Turkish Lira', symbol: '₺', rate: 32.1500, flag: '🇹🇷' },
  { code: 'KRW', name: 'South Korean Won', symbol: '₩', rate: 1375.5000, flag: '🇰🇷' },
  { code: 'RUB', name: 'Russian Ruble', symbol: '₽', rate: 91.2500, flag: '🇷🇺' },
  { code: 'HKD', name: 'Hong Kong Dollar', symbol: 'HK$', rate: 7.8200, flag: '🇭🇰' }
]

interface FormValues {
  amount: number
  fromCurrency: string
  toCurrency: string
}

// Styled components for enhanced visual design
const GradientHeader = styled(Box)(({ theme }) => ({
  background: `linear-gradient(135deg, ${theme.palette.primary.main} 0%, ${theme.palette.primary.dark} 100%)`,
  padding: theme.spacing(3, 4),
  borderRadius: theme.spacing(2),
  marginBottom: theme.spacing(4),
  position: 'relative',
  overflow: 'hidden',
  '&::before': {
    content: '""',
    position: 'absolute',
    top: -50,
    right: -50,
    width: 200,
    height: 200,
    borderRadius: '50%',
    background: alpha(theme.palette.common.white, 0.05),
  },
  '&::after': {
    content: '""',
    position: 'absolute',
    bottom: -30,
    left: -30,
    width: 150,
    height: 150,
    borderRadius: '50%',
    background: alpha(theme.palette.common.white, 0.03),
  }
}))

const ResultPaper = styled(Paper)(({ theme }) => ({
  padding: theme.spacing(4),
  background: `linear-gradient(135deg, ${theme.palette.primary.main} 0%, ${theme.palette.primary.dark} 100%)`,
  color: theme.palette.common.white,
  textAlign: 'center',
  borderRadius: theme.spacing(2),
  position: 'relative',
  overflow: 'hidden',
  transition: 'all 0.3s ease',
  '&::before': {
    content: '""',
    position: 'absolute',
    top: -60,
    right: -60,
    width: 120,
    height: 120,
    borderRadius: '50%',
    background: alpha(theme.palette.common.white, 0.05),
  },
  '&::after': {
    content: '""',
    position: 'absolute',
    bottom: -40,
    left: -40,
    width: 100,
    height: 100,
    borderRadius: '50%',
    background: alpha(theme.palette.common.white, 0.03),
  }
}))

const StyledCard = styled(Card)(({ theme }) => ({
  height: '100%',
  borderRadius: theme.spacing(2),
  transition: 'all 0.3s ease',
  '&:hover': {
    boxShadow: theme.shadows[4],
  }
}))

const LastUpdated = styled(Box)(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
  gap: theme.spacing(1),
  color: theme.palette.text.secondary,
  fontSize: '0.75rem',
  padding: theme.spacing(0.5, 1.5),
  backgroundColor: alpha(theme.palette.background.default, 0.6),
  borderRadius: theme.spacing(1),
}))

// Styled DataGrid
const StyledDataGrid = styled(DataGrid)(({ theme }) => ({
  border: 'none',
  '& .MuiDataGrid-columnHeaders': {
    backgroundColor: alpha(theme.palette.primary.main, 0.04),
    borderBottom: `2px solid ${theme.palette.primary.main}`,
    fontWeight: 600,
    color: theme.palette.text.secondary,
  },
  '& .MuiDataGrid-columnHeader': {
    padding: theme.spacing(1.5, 2),
  },
  '& .MuiDataGrid-columnHeaderTitle': {
    fontWeight: 600,
    fontSize: '0.875rem',
  },
  '& .MuiDataGrid-cell': {
    padding: theme.spacing(1.5, 2),
    borderBottom: `1px solid ${alpha(theme.palette.divider, 0.6)}`,
  },
  '& .MuiDataGrid-row': {
    cursor: 'pointer',
    transition: 'all 0.2s ease',
    '&:hover': {
      backgroundColor: alpha(theme.palette.primary.main, 0.04),
    },
    '&.Mui-selected': {
      backgroundColor: alpha(theme.palette.primary.main, 0.08),
      '&:hover': {
        backgroundColor: alpha(theme.palette.primary.main, 0.12),
      },
      '&::before': {
        content: '""',
        position: 'absolute',
        left: 0,
        top: 0,
        bottom: 0,
        width: 3,
        backgroundColor: theme.palette.primary.main,
      }
    }
  },
  '& .MuiDataGrid-row--hover': {
    backgroundColor: alpha(theme.palette.primary.main, 0.04),
  },
  '& .MuiDataGrid-footerContainer': {
    borderTop: 'none',
    padding: theme.spacing(1, 0),
  },
  '& .MuiDataGrid-virtualScroller': {
    '&::-webkit-scrollbar': {
      width: 6,
      height: 6,
    },
    '&::-webkit-scrollbar-track': {
      background: alpha(theme.palette.primary.main, 0.05),
      borderRadius: 10,
    },
    '&::-webkit-scrollbar-thumb': {
      background: alpha(theme.palette.primary.main, 0.2),
      borderRadius: 10,
      '&:hover': {
        background: alpha(theme.palette.primary.main, 0.3),
      },
    },
  },
}))

const FXManager = () => {
  const theme = useTheme()
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'))

  // const isTablet = useMediaQuery(theme.breakpoints.down('md'))
  
  const [baseCurrency, setBaseCurrency] = useState<string>('USD')
  const [exchangedAmount, setExchangedAmount] = useState<number>(0)
  const [exchangeRate, setExchangeRate] = useState<number>(1)
  const [loading, setLoading] = useState<boolean>(false)
  const [tableLoading, setTableLoading] = useState<boolean>(false)
  const [lastUpdated, setLastUpdated] = useState<string>(new Date().toLocaleString())
  const [selectedCurrency, setSelectedCurrency] = useState<string | null>(null)
  const [pageSize, setPageSize] = useState<number>(10)

  const {
    control,
    watch,
    setValue,
    getValues,
    formState: { errors }
  } = useForm<FormValues>({
    defaultValues: {
      amount: 100,
      fromCurrency: 'USD',
      toCurrency: 'EUR'
    }
  })

  const amount = watch('amount')
  const fromCurrency = watch('fromCurrency')
  const toCurrency = watch('toCurrency')

  // Helper: Get exchange rate between two currencies
  const getExchangeRate = useCallback((from: string, to: string): number => {
    const fromRate = currencies.find(c => c.code === from)?.rate || 1
    const toRate = currencies.find(c => c.code === to)?.rate || 1
    return toRate / fromRate
  }, [])

  // Helper: Format currency
  const formatCurrency = useCallback((value: number, currencyCode: string) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: currencyCode,
      minimumFractionDigits: 2,
      maximumFractionDigits: 2
    }).format(value)
  }, [])

  // Helper: Get currency symbol
  const getCurrencySymbol = useCallback((currencyCode: string) => {
    return currencies.find(c => c.code === currencyCode)?.symbol || '$'
  }, [])

  // Helper: Get currency by code
  const getCurrency = useCallback((code: string) => {
    return currencies.find(c => c.code === code)
  }, [])

  // Update last updated time
  const updateLastUpdated = useCallback(() => {
    setLastUpdated(new Date().toLocaleString())
  }, [])

  // Calculate exchanged amount
  const calculateExchange = useCallback(() => {
    if (!amount || amount <= 0) {
      setExchangedAmount(0)
      return
    }
    
    setLoading(true)
    setTimeout(() => {
      const rate = getExchangeRate(fromCurrency, toCurrency)
      setExchangeRate(rate)
      const result = amount * rate
      setExchangedAmount(result)
      setLoading(false)
      updateLastUpdated()
    }, 300)
  }, [amount, fromCurrency, toCurrency, getExchangeRate, updateLastUpdated])

  // Update exchange rate when currencies change
  useEffect(() => {
    if (amount > 0) {
      calculateExchange()
    } else {
      setExchangeRate(getExchangeRate(fromCurrency, toCurrency))
      setExchangedAmount(0)
    }
  }, [fromCurrency, toCurrency, amount, calculateExchange, getExchangeRate])

  // Swap currencies
  const handleSwapCurrencies = useCallback(() => {
    const currentFrom = getValues('fromCurrency')
    const currentTo = getValues('toCurrency')
    setValue('fromCurrency', currentTo)
    setValue('toCurrency', currentFrom)
  }, [getValues, setValue])

  // Handle currency row click from table
  const handleCurrencyRowClick = useCallback((currencyCode: string) => {
    setSelectedCurrency(currencyCode)
    setValue('fromCurrency', baseCurrency)
    setValue('toCurrency', currencyCode)
    
    setTimeout(() => {
      calculateExchange()
    }, 100)
  }, [baseCurrency, setValue, calculateExchange])

  // Handle convert button click from table
  const handleConvertFromTable = useCallback((currencyCode: string) => {
    handleCurrencyRowClick(currencyCode)
  }, [handleCurrencyRowClick])

  // Handle base currency change
  const handleBaseCurrencyChange = useCallback((newBase: string) => {
    setTableLoading(true)
    setBaseCurrency(newBase)
    setSelectedCurrency(null)
    setTimeout(() => {
      setTableLoading(false)
      updateLastUpdated()
    }, 300)
  }, [updateLastUpdated])

  // Get rates based on base currency
  const getRatesForBase = useCallback((baseCode: string) => {
    const baseRate = currencies.find(c => c.code === baseCode)?.rate || 1
    return currencies
      .filter(currency => currency.code !== baseCode)
      .map(currency => ({
        id: currency.code,
        ...currency,
        rateToBase: currency.rate / baseRate,
        rateFromBase: baseRate / currency.rate,
        pair: `${baseCode} → ${currency.code}`,
      }))
  }, [])

  const ratesData = useMemo(() => getRatesForBase(baseCurrency), [baseCurrency, getRatesForBase])

  // Format rate display
  const formatRateDisplay = useCallback((targetCurrency: string) => {
    const baseRate = currencies.find(c => c.code === baseCurrency)?.rate || 1
    const targetRate = currencies.find(c => c.code === targetCurrency)?.rate || 1
    const rate = targetRate / baseRate
    const symbol = getCurrencySymbol(targetCurrency)
    return `${symbol} ${rate.toFixed(4)}`
  }, [baseCurrency, getCurrencySymbol])

  // DataGrid Columns Definition - Fixed widths to prevent shifting
  const columns: GridColDef[] = useMemo(() => {
    const baseColDef: Partial<GridColDef> = {
      sortable: true,
      filterable: false,
      disableColumnMenu: true,
    }

    return [
      {
        ...baseColDef,
        field: 'currency',
        headerName: 'Currency',
        width: 200,
        minWidth: 180,
        flex: 0.3,
        renderCell: (params: GridCellParams) => {
          const currency = params.row as any
          return (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
              <Typography fontSize={22}>{currency.flag}</Typography>
              <Box>
                <Typography fontWeight={600} variant="body2">
                  {currency.code}
                </Typography>
                <Typography variant='caption' color='text.secondary' sx={{ display: { xs: 'none', sm: 'block' } }}>
                  {currency.name}
                </Typography>
              </Box>
            </Box>
          )
        }
      },
      {
        ...baseColDef,
        field: 'pair',
        headerName: 'Pair',
        width: 180,
        minWidth: 140,
        flex: 0.25,
        renderCell: (params: GridCellParams) => {
          const currency = params.row as any
          return (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
              <Typography variant='body2' color='text.secondary' fontWeight={500}>
                {baseCurrency}
              </Typography>
              <Icon icon='ri:arrow-right-line' fontSize={14} color={theme.palette.text.secondary} />
              <Typography variant='body2' fontWeight={600}>
                {currency.code}
              </Typography>
            </Box>
          )
        }
      },
      {
        ...baseColDef,
        field: 'rate',
        headerName: 'Current Rate',
        width: 220,
        minWidth: 180,
        flex: 0.35,
        renderCell: (params: GridCellParams) => {
          const currency = params.row as any
          const rate = formatRateDisplay(currency.code)
          return (
            <Box>
              <Typography fontWeight={600} variant="body2">
                {rate}
              </Typography>
              <Typography variant='caption' color='text.secondary'>
                1 {baseCurrency} = {rate} {currency.code}
              </Typography>
            </Box>
          )
        }
      },
      {
        ...baseColDef,
        field: 'action',
        headerName: 'Action',
        width: 100,
        minWidth: 80,
        flex: 0.1,
        renderCell: (params: GridCellParams) => {
          const currency = params.row as any
          return (
            <Tooltip title={`Convert to ${currency.code}`}>
              <IconButton
                size="small"
                onClick={(e) => {
                  e.stopPropagation()
                  handleConvertFromTable(currency.code)
                }}
                sx={{
                  backgroundColor: alpha(theme.palette.primary.main, 0.08),
                  '&:hover': {
                    backgroundColor: alpha(theme.palette.primary.main, 0.16),
                  }
                }}
              >
                <Icon icon='ri:arrow-right-line' fontSize={18} />
              </IconButton>
            </Tooltip>
          )
        }
      }
    ]
  }, [baseCurrency, theme, formatRateDisplay, handleConvertFromTable])

  // Handle row click
  const handleRowClick = useCallback((params: GridRowParams) => {
    const currency = params.row as any
    handleCurrencyRowClick(currency.code)
  }, [handleCurrencyRowClick])

  return (
    <Box sx={{ p: { xs: 2, sm: 3, md: 5 }, maxWidth: '1600px', mx: 'auto' }}>
      <Grid container spacing={4}>
        {/* Header Section */}
        <Grid item xs={12}>
          <GradientHeader>
            <Box sx={{ display: 'flex', flexDirection: { xs: 'column', md: 'row' }, alignItems: { xs: 'flex-start', md: 'center' }, justifyContent: 'space-between', gap: 2 }}>
              <Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 1 }}>
                  <Icon icon='ri:exchange-dollar-line' fontSize={28} style={{ color: 'white', opacity: 0.9 }} />
                  <Typography variant='h4' sx={{ fontWeight: 700, color: 'white' }}>
                    Current FX Balance
                  </Typography>
                  <Chip 
                    label="LIVE"
                    size="small"
                    sx={{ 
                      bgcolor: alpha(theme.palette.success.main, 0.3),
                      color: 'white',
                      fontWeight: 700,
                      fontSize: '0.65rem',
                      height: 20
                    }}
                    icon={<Box sx={{ width: 6, height: 6, bgcolor: '#4caf50', borderRadius: '50%', animation: 'pulse 1.5s infinite' }} />}
                  />
                </Box>
                <Typography variant='body2' sx={{ color: alpha(theme.palette.common.white, 0.85), maxWidth: 600 }}>
                  Instantly convert between 20+ global currencies with real-time exchange rates. Professional institutional tools for modern financial management.
                </Typography>
              </Box>
            </Box>
          </GradientHeader>
        </Grid>

        {/* Exchange Rate Table Section */}
        <Grid item xs={12} md={7}>
          <StyledCard>
            <CardContent sx={{ p: { xs: 2, sm: 3 } }}>
              <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2.5, flexWrap: 'wrap', gap: 2 }}>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
                  <Icon icon='ri:table-line' fontSize={22} color={theme.palette.primary.main} />
                  <Typography variant='h6' sx={{ color: 'primary.main', fontWeight: 600 }}>
                    Market Rates
                  </Typography>
                </Box>
                <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
                  <LastUpdated>
                    <Icon icon='ri:calendar-line' fontSize={14} />
                    Last updated: {lastUpdated}
                  </LastUpdated>
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Typography variant='body2' sx={{ color: 'text.secondary', fontWeight: 500, fontSize: '0.75rem' }}>
                      Base:
                    </Typography>
                    <TextField
                      select
                      size="small"
                      value={baseCurrency}
                      onChange={(e) => handleBaseCurrencyChange(e.target.value)}
                      sx={{ 
                        width: 100,
                        '& .MuiSelect-select': {
                          display: 'flex',
                          alignItems: 'center',
                          gap: 0.5,
                          py: 0.5,
                          fontSize: '0.85rem',
                          fontWeight: 600
                        }
                      }}
                      SelectProps={{
                        renderValue: (value) => {
                          const currency = getCurrency(value as string)
                          return (
                            <Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
                              <Typography>{currency?.flag}</Typography>
                              <Typography fontWeight={600}>{value as string}</Typography>
                            </Box>
                          )
                        }
                      }}
                    >
                      {currencies.map((currency) => (
                        <MenuItem key={currency.code} value={currency.code}>
                          <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                            <Typography>{currency.flag}</Typography>
                            <Typography fontWeight={500}>{currency.code}</Typography>
                          </Box>
                        </MenuItem>
                      ))}
                    </TextField>
                  </Box>
                </Box>
              </Box>

              {tableLoading ? (
                <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
                  <CircularProgress size={40} />
                </Box>
              ) : (
                <Box sx={{ height: 450, width: '100%' }}>
                  <StyledDataGrid
                    rows={ratesData}
                    columns={columns}
                    pageSize={pageSize}
                    onPageSizeChange={(newPageSize) => setPageSize(newPageSize)}
                    rowsPerPageOptions={[5, 10, 25, 50]}
                    onRowClick={handleRowClick}
                    selectionModel={selectedCurrency ? [selectedCurrency] : []}
                    getRowId={(row) => row.code}
                    disableSelectionOnClick
                    disableColumnSelector
                    disableDensitySelector
                    hideFooterSelectedRowCount
                    autoHeight={false}
                    sx={{
                      '& .MuiDataGrid-row': {
                        '&.Mui-selected': {
                          backgroundColor: alpha(theme.palette.primary.main, 0.08),
                          '&:hover': {
                            backgroundColor: alpha(theme.palette.primary.main, 0.12),
                          }
                        }
                      }
                    }}
                  />
                </Box>
              )}

              <Divider sx={{ my: 2 }} />
              
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 1 }}>
                <Typography variant='caption' color='text.secondary'>
                  <Icon icon='ri:information-line' fontSize={14} style={{ verticalAlign: 'middle' }} />
                  {' '}Click any currency row to auto-fill the converter
                </Typography>
                <Chip 
                  size='small' 
                  label={`${ratesData.length} currency pairs`}
                  color='primary'
                  variant='outlined'
                  sx={{ fontWeight: 500, fontSize: '0.7rem', height: 24 }}
                />
              </Box>
            </CardContent>
          </StyledCard>
        </Grid>

        {/* Currency Converter Section */}
        <Grid item xs={12} md={5}>
          <StyledCard>
            <CardContent sx={{ p: { xs: 2, sm: 3 } }}>
              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5, mb: 3 }}>
                <Icon icon='ri:calculator-line' fontSize={22} color={theme.palette.primary.main} />
                <Typography variant='h6' sx={{ color: 'primary.main', fontWeight: 600 }}>
                  Currency Converter
                </Typography>
              </Box>

              <Box sx={{ mb: 3 }}>
                <Controller
                  name='amount'
                  control={control}
                  rules={{ 
                    required: 'Amount is required',
                    min: { value: 0.01, message: 'Amount must be greater than 0' }
                  }}
                  render={({ field }) => (
                    <TextField
                      {...field}
                      fullWidth
                      type='number'
                      label='Amount'
                      placeholder='Enter amount'
                      error={!!errors.amount}
                      helperText={errors.amount?.message}
                      InputProps={{
                        startAdornment: <InputAdornment position='start'>{getCurrencySymbol(fromCurrency)}</InputAdornment>
                      }}
                      sx={{ 
                        '& .MuiOutlinedInput-root': {
                          borderRadius: 2,
                          backgroundColor: alpha(theme.palette.background.default, 0.5)
                        }
                      }}
                    />
                  )}
                />
              </Box>

              <Box sx={{ position: 'relative', mb: 3 }}>
                <Grid container spacing={2} alignItems='center'>
                  <Grid item xs={12} sm={5}>
                    <Controller
                      name='fromCurrency'
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          select
                          fullWidth
                          label="From"
                          size="medium"
                          sx={{ 
                            '& .MuiOutlinedInput-root': {
                              borderRadius: 2,
                              backgroundColor: alpha(theme.palette.background.default, 0.5)
                            }
                          }}
                        >
                          {currencies.map((currency) => (
                            <MenuItem key={currency.code} value={currency.code}>
                              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
                                <Typography>{currency.flag}</Typography>
                                <Box>
                                  <Typography fontWeight={500}>{currency.code}</Typography>
                                  <Typography variant='caption' color='text.secondary' sx={{ display: { xs: 'none', sm: 'block' } }}>
                                    {currency.name}
                                  </Typography>
                                </Box>
                              </Box>
                            </MenuItem>
                          ))}
                        </TextField>
                      )}
                    />
                  </Grid>

                  <Grid item xs={12} sm={2} sx={{ textAlign: 'center' }}>
                    <Zoom in key={fromCurrency + toCurrency}>
                      <IconButton 
                        onClick={handleSwapCurrencies} 
                        sx={{ 
                          bgcolor: 'primary.main', 
                          color: 'white',
                          '&:hover': { 
                            bgcolor: 'primary.dark',
                            transform: 'rotate(180deg)',
                            transition: 'transform 0.3s ease'
                          },
                          transition: 'all 0.3s ease',
                          width: 44,
                          height: 44
                        }}
                      >
                        <Icon icon='ri:swap-line' fontSize={20} />
                      </IconButton>
                    </Zoom>
                  </Grid>

                  <Grid item xs={12} sm={5}>
                    <Controller
                      name='toCurrency'
                      control={control}
                      render={({ field }) => (
                        <TextField
                          {...field}
                          select
                          fullWidth
                          label="To"
                          size="medium"
                          sx={{ 
                            '& .MuiOutlinedInput-root': {
                              borderRadius: 2,
                              backgroundColor: alpha(theme.palette.background.default, 0.5)
                            }
                          }}
                        >
                          {currencies.map((currency) => (
                            <MenuItem key={currency.code} value={currency.code}>
                              <Box sx={{ display: 'flex', alignItems: 'center', gap: 1.5 }}>
                                <Typography>{currency.flag}</Typography>
                                <Box>
                                  <Typography fontWeight={500}>{currency.code}</Typography>
                                  <Typography variant='caption' color='text.secondary' sx={{ display: { xs: 'none', sm: 'block' } }}>
                                    {currency.name}
                                  </Typography>
                                </Box>
                              </Box>
                            </MenuItem>
                          ))}
                        </TextField>
                      )}
                    />
                  </Grid>
                </Grid>
              </Box>

              {/* Exchange Rate Display */}
              <Fade in key={fromCurrency + toCurrency}>
                <Alert 
                  severity='info' 
                  sx={{ 
                    my: 2.5,
                    borderRadius: 2,
                    '& .MuiAlert-icon': {
                      alignItems: 'center'
                    }
                  }}
                  icon={<Icon icon='ri:exchange-line' />}
                >
                  <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 1 }}>
                    <Typography variant='body2' fontWeight={500} color='text.secondary'>
                      Exchange Rate
                    </Typography>
                    <Typography variant='h6' fontWeight={700} color='primary.main'>
                      1 {fromCurrency} = {exchangeRate.toFixed(4)} {toCurrency}
                    </Typography>
                  </Box>
                </Alert>
              </Fade>

              {/* Exchanged Amount */}
              <ResultPaper elevation={3}>
                <Typography variant='body2' sx={{ mb: 0.5, opacity: 0.9, textTransform: 'uppercase', letterSpacing: 1.5, fontSize: '0.7rem' }}>
                  Converted Amount
                </Typography>
                {loading ? (
                  <CircularProgress size={40} color='inherit' />
                ) : (
                  <Fade in key={exchangedAmount}>
                    <Typography variant={isMobile ? 'h4' : 'h2'} sx={{ fontWeight: 700 }}>
                      {amount > 0 && amount !== undefined ? formatCurrency(exchangedAmount, toCurrency) : `${getCurrencySymbol(toCurrency)} 0.00`}
                    </Typography>
                  </Fade>
                )}
                {!loading && amount > 0 && (
                  <Typography variant='caption' sx={{ opacity: 0.8, mt: 0.5, display: 'block' }}>
                    Updated {new Date().toLocaleTimeString()}
                  </Typography>
                )}
              </ResultPaper>

              {/* Convert Button */}
              <Button
                fullWidth
                size='large'
                variant='contained'
                onClick={calculateExchange}
                disabled={!amount || amount <= 0 || loading}
                sx={{ 
                  mt: 2.5,
                  py: 1.5,
                  borderRadius: 2,
                  fontWeight: 600,
                  background: `linear-gradient(135deg, ${theme.palette.primary.main} 0%, ${theme.palette.primary.dark} 100%)`,
                  '&:hover': {
                    transform: 'translateY(-2px)',
                    boxShadow: theme.shadows[4]
                  },
                  transition: 'all 0.3s ease'
                }}
              >
                {loading ? <CircularProgress size={24} color='inherit' /> : (
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                    <Icon icon='ri:arrow-right-circle-line' />
                    Convert Currency
                  </Box>
                )}
              </Button>

              {/* Info Text */}
              <Typography variant='caption' sx={{ mt: 2, display: 'block', textAlign: 'center', color: 'text.secondary' }}>
                <Icon icon='ri:shield-check-line' fontSize={12} style={{ verticalAlign: 'middle', marginRight: 4 }} />
                Rates are updated every 15 seconds. Actual conversion rate may vary at the time of transaction.
              </Typography>
            </CardContent>
          </StyledCard>
        </Grid>
      </Grid>
    </Box>
  )
}

FXManager.acl = {
  action: 'read',
  subject: 'user-management'
}

export default FXManager