import React, { useState, useEffect } from 'react'

// ** MUI Imports
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 Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
import FormControl from '@mui/material/FormControl'
import InputLabel from '@mui/material/InputLabel'
import Select from '@mui/material/Select'
import MenuItem from '@mui/material/MenuItem'
import Grid from '@mui/material/Grid'
import IconButton from '@mui/material/IconButton'
import FormControlLabel from '@mui/material/FormControlLabel'
import Radio from '@mui/material/Radio'
import RadioGroup from '@mui/material/RadioGroup'
import FormLabel from '@mui/material/FormLabel'

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

// ** Types
import { SourceOfFundType, EventType, EventBasedSaving } from '../types'

interface EventBasedModalProps {
  open: boolean
  onClose: () => void
  onSave: (data: any) => void
  editData?: EventBasedSaving | null
}

const EventBasedModal = ({ open, onClose, onSave, editData }: EventBasedModalProps) => {
  const [eventType, setEventType] = useState<EventType>('wallet-to-wallet-transfer')
  const [sourceOfFund, setSourceOfFund] = useState<SourceOfFundType>('wallet')
  const [savingType, setSavingType] = useState<'fixed' | 'percentage'>('fixed')
  const [amount, setAmount] = useState<string>('')
  const [percentage, setPercentage] = useState<string>('')

  useEffect(() => {
    if (editData) {
      setEventType(editData.eventType)
      setSourceOfFund(editData.sourceOfFund)
      setSavingType(editData.savingType)
      if (editData.savingType === 'fixed') {
        setAmount(editData.amount.toString())
        setPercentage('')
      } else {
        setPercentage(editData.percentage.toString())
        setAmount('')
      }
    } else {
      setEventType('wallet-to-wallet-transfer')
      setSourceOfFund('wallet')
      setSavingType('fixed')
      setAmount('')
      setPercentage('')
    }
  }, [editData, open])

  const handleSave = () => {
    if (savingType === 'fixed') {
      if (!amount || parseFloat(amount) <= 0) return
      onSave({
        eventType,
        sourceOfFund,
        savingType,
        amount: parseFloat(amount),
        percentage: 0,
        balance: parseFloat(amount)
      })
    } else {
      if (!percentage || parseFloat(percentage) <= 0 || parseFloat(percentage) > 100) return
      onSave({
        eventType,
        sourceOfFund,
        savingType,
        amount: 0,
        percentage: parseFloat(percentage),
        balance: 0
      })
    }
    handleClose()
  }

  const handleClose = () => {
    setEventType('wallet-to-wallet-transfer')
    setSourceOfFund('wallet')
    setSavingType('fixed')
    setAmount('')
    setPercentage('')
    onClose()
  }

  const eventTypes: EventType[] = [
    'wallet-to-wallet-transfer',
    'adding-money-to-wallet',
    'sending-money-outoff-wallet',
    'future-transaction',
    'currency-conversion',
    'bill-payment',
    'travel-booking'
  ]

  const formatEventLabel = (event: string) => {
    return event.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')
  }

  return (
    <Dialog open={open} onClose={handleClose} maxWidth='sm' fullWidth>
      <DialogTitle>
        Saving Details
        <IconButton
          aria-label='close'
          onClick={handleClose}
          sx={{ position: 'absolute', right: 8, top: 8 }}
        >
          <Icon icon='tabler:x' />
        </IconButton>
      </DialogTitle>
      <DialogContent>
        <Grid container spacing={4} sx={{ mt: 1 }}>
          <Grid item xs={12}>
            <FormControl fullWidth>
              <InputLabel>Source Of Funds</InputLabel>
              <Select value={sourceOfFund} label='Source Of Funds' onChange={(e) => setSourceOfFund(e.target.value as SourceOfFundType)}>
                <MenuItem value='wallet'>Wallet</MenuItem>
                <MenuItem value='bank'>Bank</MenuItem>
                <MenuItem value='card'>Card</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12}>
            <FormControl fullWidth>
              <InputLabel>Event Type</InputLabel>
              <Select value={eventType} label='Event Type' onChange={(e) => setEventType(e.target.value as EventType)}>
                {eventTypes.map((event) => (
                  <MenuItem key={event} value={event}>
                    {formatEventLabel(event)}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12}>
            <FormLabel component="legend">Saving Type</FormLabel>
            <RadioGroup
              row
              value={savingType}
              onChange={(e) => setSavingType(e.target.value as 'fixed' | 'percentage')}
            >
              <FormControlLabel value='fixed' control={<Radio />} label='Saving Amount' />
              <FormControlLabel value='percentage' control={<Radio />} label='Percentage Of Transaction' />
            </RadioGroup>
          </Grid>
          {savingType === 'fixed' ? (
            <Grid item xs={12}>
              <TextField
                fullWidth
                type='number'
                label='Amount'
                value={amount}
                onChange={(e) => setAmount(e.target.value)}
                InputProps={{ inputProps: { min: 0, step: 0.01 } }}
              />
            </Grid>
          ) : (
            <Grid item xs={12}>
              <TextField
                fullWidth
                type='number'
                label='Percentage (%)'
                value={percentage}
                onChange={(e) => setPercentage(e.target.value)}
                InputProps={{ inputProps: { min: 0, max: 100, step: 0.01 } }}
              />
            </Grid>
          )}
        </Grid>
      </DialogContent>
      <DialogActions>
        <Button onClick={handleClose} color='secondary'>
          Cancel
        </Button>
        <Button onClick={handleSave} variant='contained'>
          Save
        </Button>
      </DialogActions>
    </Dialog>
  )
}

export default EventBasedModal