import React from 'react'

// ** MUI Imports
import Card from '@mui/material/Card'
import Box from '@mui/material/Box'
import Chip from '@mui/material/Chip'
import Tooltip from '@mui/material/Tooltip'
import Typography from '@mui/material/Typography'
import { DataGrid } from '@mui/x-data-grid'

interface TransactionTableProps {
  data: any[]
  visibleColumns: {
    srNo: boolean
    date: boolean
    detailsParticular: boolean
    transactionId: boolean
    description: boolean
    transactionType: boolean
    debit: boolean
    credit: boolean
    ongoingBalance: boolean
    closingBalance: boolean
    status: boolean
  }
  pageSize: number
  onPageSizeChange: (size: number) => void
  onView?: (row: any) => void
  onEdit?: (row: any) => void
  onDelete?: (row: any) => void
  onToggleStatus?: (row: any) => void
}

const TransactionTable = ({
  data,
  visibleColumns,
  pageSize,
  onPageSizeChange,
}: TransactionTableProps) => {
  const formatCurrency = (amount: number | null) => {
    if (!amount) return '-'
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 2
    }).format(amount)
  }

  const getStatusColor = (status: string) => {
    switch (status.toLowerCase()) {
      case 'completed':
        return 'success'
      case 'pending':
        return 'warning'
      case 'failed':
        return 'error'
      default:
        return 'default'
    }
  }

  const getTransactionTypeColor = (type: string) => {
    switch (type.toLowerCase()) {
      case 'bank':
        return 'primary'
      case 'cash':
        return 'success'
      case 'wallet':
        return 'warning'
      default:
        return 'default'
    }
  }

  const formatDateTime = (dateTime: string) => {
    if (!dateTime) return '-'
    const date = new Date(dateTime)
    return date.toLocaleString('en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  }

  // Define DataGrid columns
  const columns = [
    { 
      field: 'srNo', 
      headerName: 'SR. NO', 
      flex: 0.06, 
      minWidth: 70, 
      renderCell: ({ row }: any) => (
        <Typography variant="body2" sx={{ fontWeight: 500 }}>
          {row.srNo}
        </Typography>
      ), 
      hide: !visibleColumns.srNo 
    },
    { 
      field: 'date', 
      headerName: 'Date & Time', 
      flex: 0.15, 
      minWidth: 170, 
      renderCell: ({ row }: any) => (
        <Tooltip title={formatDateTime(row.date)}>
          <Typography variant="body2" sx={{ fontSize: '0.75rem' }}>
            {formatDateTime(row.date)}
          </Typography>
        </Tooltip>
      ), 
      hide: !visibleColumns.date 
    },
    { 
      field: 'detailsParticular', 
      headerName: 'Details Particular/Product', 
      flex: 0.18, 
      minWidth: 200, 
      renderCell: ({ row }: any) => (
        <Box sx={{ display: 'flex', flexDirection: 'column' }}>
          <Typography variant="body2" sx={{ fontWeight: 500, fontSize: '0.8rem' }}>
            {row.detailsParticular || row.description}
          </Typography>
          {row.productCode && (
            <Typography variant="caption" sx={{ color: 'text.secondary', fontSize: '0.7rem' }}>
              Code: {row.productCode}
            </Typography>
          )}
        </Box>
      ), 
      hide: !visibleColumns.detailsParticular 
    },
    { 
      field: 'transactionId', 
      headerName: 'Transaction ID', 
      flex: 0.12, 
      minWidth: 130, 
      renderCell: ({ row }: any) => (
        <Tooltip title={row.transactionId}>
          <Typography variant="body2" sx={{ fontWeight: 500, color: 'primary.main', fontSize: '0.75rem' }}>
            {row.transactionId.length > 15 ? `${row.transactionId.slice(0, 15)}...` : row.transactionId}
          </Typography>
        </Tooltip>
      ), 
      hide: !visibleColumns.transactionId 
    },
    { 
      field: 'description', 
      headerName: 'Description', 
      flex: 0.18, 
      minWidth: 200, 
      renderCell: ({ row }: any) => (
        <Tooltip title={row.description}>
          <Typography variant="body2" sx={{ fontSize: '0.75rem' }}>
            {row.description && row.description.length > 50 ? `${row.description.substring(0, 50)}...` : row.description || '-'}
          </Typography>
        </Tooltip>
      ), 
      hide: !visibleColumns.description 
    },
    { 
      field: 'transactionType', 
      headerName: 'Transaction Type', 
      flex: 0.1, 
      minWidth: 120, 
      renderCell: ({ row }: any) => (
        <Chip 
          label={row.transactionType} 
          color={getTransactionTypeColor(row.transactionType)} 
          size="small" 
          sx={{ fontWeight: 500, fontSize: '0.75rem', minWidth: 70 }} 
        />
      ), 
      hide: !visibleColumns.transactionType 
    },
    { 
      field: 'debit', 
      headerName: 'Debit', 
      flex: 0.09, 
      minWidth: 100, 
      renderCell: ({ row }: any) => (
        row.debit ? (
          <Typography variant="body2" sx={{ color: 'error.main', fontWeight: 600, fontSize: '0.75rem' }}>
            {formatCurrency(row.debit)}
          </Typography>
        ) : <Typography variant="body2" sx={{ fontSize: '0.75rem' }}>-</Typography>
      ), 
      hide: !visibleColumns.debit 
    },
    { 
      field: 'credit', 
      headerName: 'Credit', 
      flex: 0.09, 
      minWidth: 100, 
      renderCell: ({ row }: any) => (
        row.credit ? (
          <Typography variant="body2" sx={{ color: 'success.main', fontWeight: 600, fontSize: '0.75rem' }}>
            {formatCurrency(row.credit)}
          </Typography>
        ) : <Typography variant="body2" sx={{ fontSize: '0.75rem' }}>-</Typography>
      ), 
      hide: !visibleColumns.credit 
    },
    { 
      field: 'ongoingBalance', 
      headerName: 'Ongoing Balance', 
      flex: 0.1, 
      minWidth: 120, 
      renderCell: ({ row }: any) => (
        <Typography variant="body2" sx={{ fontWeight: 500, fontSize: '0.75rem' }}>
          {formatCurrency(row.ongoingBalance)}
        </Typography>
      ), 
      hide: !visibleColumns.ongoingBalance 
    },
    { 
      field: 'closingBalance', 
      headerName: 'Closing Balance', 
      flex: 0.1, 
      minWidth: 120, 
      renderCell: ({ row }: any) => (
        <Typography variant="body2" sx={{ fontWeight: 600, color: 'primary.main', fontSize: '0.75rem' }}>
          {formatCurrency(row.closingBalance)}
        </Typography>
      ), 
      hide: !visibleColumns.closingBalance 
    },
    { 
      field: 'status', 
      headerName: 'Status', 
      flex: 0.12, 
      minWidth: 110, 
      renderCell: ({ row }: any) => (
        <Chip 
          label={row.status} 
          color={getStatusColor(row.status)} 
          size="medium"
          sx={{ 
            fontWeight: 500, 
            fontSize: '0.8rem',
            width: 'auto',
            minWidth: '85px',
            '& .MuiChip-label': {
              padding: '0 12px',
              whiteSpace: 'nowrap',
              overflow: 'visible',
              textOverflow: 'clip'
            }
          }} 
        />
      ), 
      hide: !visibleColumns.status 
    }
  ].filter(col => !col.hide)

  return (
    <Card>
      <Box sx={{ height: 'calc(100vh - 300px)', width: '100%' }}>
        <DataGrid
          rows={data}
          columns={columns}
          pageSize={pageSize}
          rowsPerPageOptions={[10, 25, 50, 100]}
          autoHeight
          disableSelectionOnClick
          sortingOrder={['asc', 'desc']}
          onPageSizeChange={(newPageSize: number) => onPageSizeChange(newPageSize)}
          sx={{
            '& .MuiDataGrid-columnHeaders': {
              backgroundColor: 'action.hover',
              fontWeight: 600,
              fontSize: '0.85rem'
            },
            '& .MuiDataGrid-cell': { 
              py: 1.5,
              fontSize: '0.75rem'
            },
            '& .MuiDataGrid-row': {
              minHeight: '52px !important'
            },
            '& .MuiDataGrid-row:hover': {
              backgroundColor: 'action.hover'
            },
            '& .MuiDataGrid-virtualScroller': {
              overflowX: 'auto'
            }
          }}
        />
      </Box>
    </Card>
  )
}

export default TransactionTable