import React, { useState } from 'react'
import {
  Card,
  Box,
  Chip,
  Tooltip,
  IconButton,
  Typography,
  Menu,
  MenuItem,
  Button
} from '@mui/material'
import { DataGrid, GridColDef } from '@mui/x-data-grid'
import Icon from 'src/@core/components/icon'
import { SwitchAccountRecord, SwitchAccountTableProps } from './types'
import toast from 'react-hot-toast'

const SwitchAccountTable: React.FC<SwitchAccountTableProps> = ({ 
  data, 
  onAddClick,
  onEdit,
  onDelete,
  onView,
  onToggleStatus
}) => {
  const [actionAnchorEl, setActionAnchorEl] = useState<null | HTMLElement>(null)
  const [selectedRow, setSelectedRow] = useState<SwitchAccountRecord | null>(null)

  const handleActionClick = (event: React.MouseEvent<HTMLElement>, row: SwitchAccountRecord) => {
    setActionAnchorEl(event.currentTarget)
    setSelectedRow(row)
  }

  const handleActionClose = () => {
    setActionAnchorEl(null)
    setSelectedRow(null)
  }

  const handleEdit = () => {
    if (onEdit && selectedRow) onEdit(selectedRow)
    else toast.success(`Editing switch account: ${selectedRow?.fromUserName}`)
    handleActionClose()
  }

  const handleDelete = () => {
    if (onDelete && selectedRow) onDelete(selectedRow)
    else toast.success(`Deleted switch account: ${selectedRow?.fromUserName}`)
    handleActionClose()
  }

  const handleViewDetails = (row: SwitchAccountRecord) => {
    if (onView) onView(row)
    else toast.success(`Viewing switch account: ${row.fromUserName}`)
  }

  const handleToggleStatus = () => {
    if (onToggleStatus && selectedRow) onToggleStatus(selectedRow)
    else toast.success(`Status toggled for account: ${selectedRow?.fromUserName}`)
    handleActionClose()
  }

  const getWalletTypeColor = (type: string) => {
    switch (type.toLowerCase()) {
      case 'bank':
        return 'primary'
      case 'crypto':
        return 'secondary'
      case 'ewallet':
        return 'success'
      default:
        return 'default'
    }
  }

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

  // Define DataGrid columns
  const columns: GridColDef[] = [
    { 
      field: 'srNo', 
      headerName: 'Sr.No', 
      width: 80, 
      renderCell: ({ row }: any) => (
        <Typography variant="body2" sx={{ fontWeight: 500 }}>
          {row.srNo}
        </Typography>
      )
    },
    { 
      field: 'fromUserName', 
      headerName: 'From User Name', 
      flex: 0.2, 
      minWidth: 150, 
      renderCell: ({ row }: any) => (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Icon icon='tabler:user-circle' fontSize={18} />
          <Typography variant="body2" sx={{ fontWeight: 500 }}>
            {row.fromUserName}
          </Typography>
        </Box>
      )
    },
    { 
      field: 'toUserName', 
      headerName: 'To User Name', 
      flex: 0.2, 
      minWidth: 150, 
      renderCell: ({ row }: any) => (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Icon icon='tabler:user-check' fontSize={18} />
          <Typography variant="body2">
            {row.toUserName}
          </Typography>
        </Box>
      )
    },
    { 
      field: 'linkWalletType', 
      headerName: 'Link Wallet Type', 
      width: 150, 
      renderCell: ({ row }: any) => (
        <Chip 
          label={row.linkWalletType} 
          size="small" 
          color={getWalletTypeColor(row.linkWalletType) as any}
          icon={<Icon icon='tabler:wallet' fontSize={16} />}
          sx={{ fontWeight: 500 }}
        />
      )
    },
    { 
      field: 'status', 
      headerName: 'Status', 
      width: 120, 
      renderCell: ({ row }: any) => (
        <Chip 
          label={row.status} 
          size="small" 
          color={getStatusColor(row.status) as any}
          sx={{ fontWeight: 500 }}
        />
      )
    },
    { 
      field: 'actions', 
      headerName: 'Action', 
      width: 120, 
      sortable: false, 
      renderCell: ({ row }: any) => (
        <Box>
          <Tooltip title="View Details">
            <IconButton size="small" onClick={() => handleViewDetails(row)} sx={{ mr: 1 }}>
              <Icon icon="tabler:eye" fontSize={20} />
            </IconButton>
          </Tooltip>
          <Tooltip title="More Actions">
            <IconButton size="small" onClick={e => handleActionClick(e, row)}>
              <Icon icon="tabler:dots-vertical" fontSize={20} />
            </IconButton>
          </Tooltip>
        </Box>
      )
    }
  ]

  return (
    <Card>
      <Box sx={{ p: 3, display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 2 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <Icon icon='tabler:table' fontSize={28} style={{ color: '#1976d2' }} />
          <Typography variant='h6' sx={{ fontWeight: 600 }}>
            Switch Account Records
          </Typography>
          <Chip 
            label={`Total: ${data.length}`} 
            size='small' 
            color='info' 
          />
        </Box>
        <Button
          variant='contained'
          startIcon={<Icon icon='tabler:plus' />}
          onClick={onAddClick}
        >
          Add Switch Account
        </Button>
      </Box>

      <Box sx={{ height: 'calc(100vh - 400px)', width: '100%', p: 3, pt: 0 }}>
        <DataGrid
          rows={data}
          columns={columns}
          pageSize={10}
          rowsPerPageOptions={[10, 25, 50, 100]}
          autoHeight
          disableSelectionOnClick
          sortingOrder={['asc', 'desc']}
          getRowId={(row) => row.id}
          sx={{
            '& .MuiDataGrid-columnHeaders': {
              backgroundColor: 'action.hover',
              fontWeight: 600,
              fontSize: '0.9rem'
            },
            '& .MuiDataGrid-cell': { 
              py: 1.5
            },
            '& .MuiDataGrid-row': {
              minHeight: '52px !important'
            },
            '& .MuiDataGrid-row:hover': {
              backgroundColor: 'action.hover'
            }
          }}
        />
      </Box>

      {/* Action Menu */}
      <Menu
        anchorEl={actionAnchorEl}
        open={Boolean(actionAnchorEl)}
        onClose={handleActionClose}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
        transformOrigin={{ vertical: 'top', horizontal: 'right' }}
        PaperProps={{ style: { minWidth: '8rem' } }}
      >
        <MenuItem onClick={handleEdit} sx={{ '& svg': { mr: 2 } }}>
          <Icon icon="tabler:edit" fontSize={20} />
          Edit
        </MenuItem>
        <MenuItem onClick={handleToggleStatus} sx={{ '& svg': { mr: 2 } }}>
          <Icon icon={selectedRow?.status === 'Active' ? 'tabler:user-x' : 'tabler:user-check'} fontSize={20} />
          {selectedRow?.status === 'Active' ? 'Deactivate' : 'Activate'}
        </MenuItem>
        <MenuItem onClick={handleDelete} sx={{ '& svg': { mr: 2 } }}>
          <Icon icon="tabler:trash" fontSize={20} />
          Delete
        </MenuItem>
      </Menu>
    </Card>
  )
}

export default SwitchAccountTable