import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/router'

// ** MUI Imports
import Box from '@mui/material/Box'
import Grid from '@mui/material/Grid'
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
import CardMedia from '@mui/material/CardMedia'
import Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Rating from '@mui/material/Rating'
import Divider from '@mui/material/Divider'
import IconButton from '@mui/material/IconButton'
import Radio from '@mui/material/Radio'
import RadioGroup from '@mui/material/RadioGroup'
import FormControlLabel from '@mui/material/FormControlLabel'
import FormControl from '@mui/material/FormControl'
import TextField from '@mui/material/TextField'
import Alert from '@mui/material/Alert'
import Icon from 'src/@core/components/icon'

// ** Dummy Data
import { hotels } from '../dummyData'

// ** Toast
import toast from 'react-hot-toast'

interface HotelBookingProps {
  id: string
}

const HotelBooking = ({ id }: HotelBookingProps) => {
  const router = useRouter()
  const { checkIn, checkOut, guests } = router.query
  const [hotel, setHotel] = useState<any>(null)
  const [selectedRoom, setSelectedRoom] = useState('')
  const [fullName, setFullName] = useState('')
  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')
  const [specialRequests, setSpecialRequests] = useState('')
  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    const foundHotel = hotels.find(h => h.id === id)
    setHotel(foundHotel)
  }, [id])

  if (!hotel) return null

  const checkInDate = checkIn ? new Date(checkIn as string) : new Date()
  const checkOutDate = checkOut ? new Date(checkOut as string) : new Date(Date.now() + 3 * 24 * 60 * 60 * 1000)
  const guestsCount = parseInt(guests as string) || 2
  const nights = Math.ceil((checkOutDate.getTime() - checkInDate.getTime()) / (1000 * 60 * 60 * 24))
  
  const selectedRoomData = hotel.rooms.find((room: any) => room.id === selectedRoom)
  const totalPrice = selectedRoomData ? selectedRoomData.price * nights : 0

  const handleConfirmBooking = () => {
    if (!selectedRoom) {
      toast.error('Please select a room type')
      return
    }
    if (!fullName || !email) {
      toast.error('Please fill in your details')
      return
    }
    
    setIsLoading(true)
    setTimeout(() => {
      toast.success(`Hotel booked successfully! Total: $${totalPrice}`)
      setIsLoading(false)
      router.push('/travel-booking')
    }, 2000)
  }

  return (
    <Box>
      <Box sx={{ display: 'flex', alignItems: 'center', mb: 4 }}>
        <IconButton onClick={() => router.back()} sx={{ mr: 2 }}>
          <Icon icon='tabler:arrow-left' />
        </IconButton>
        <Typography variant='h5'>Complete Your Booking</Typography>
      </Box>

      <Grid container spacing={4}>
        <Grid item xs={12} md={8}>
          <Card sx={{ mb: 4 }}>
            <CardContent>
              <Typography variant='h6' sx={{ mb: 3 }}>Select Room Type</Typography>
              <FormControl component="fieldset">
                <RadioGroup value={selectedRoom} onChange={(e) => setSelectedRoom(e.target.value)}>
                  {hotel.rooms.map((room: any) => (
                    <FormControlLabel
                      key={room.id}
                      value={room.id}
                      control={<Radio />}
                      disabled={!room.available}
                      label={
                        <Box sx={{ display: 'flex', justifyContent: 'space-between', width: '100%', gap: 2 }}>
                          <Box>
                            <Typography variant='body1' sx={{ fontWeight: 500 }}>{room.type}</Typography>
                            <Typography variant='caption' color='text.secondary'>Max {room.maxGuests} guests</Typography>
                          </Box>
                          <Typography variant='h6' sx={{ color: 'primary.main', fontWeight: 600 }}>
                            ${room.price}/night
                          </Typography>
                        </Box>
                      }
                      sx={{ width: '100%', mb: 2, border: 1, borderColor: 'divider', borderRadius: 2, p: 2 }}
                    />
                  ))}
                </RadioGroup>
              </FormControl>
            </CardContent>
          </Card>

          <Card>
            <CardContent>
              <Typography variant='h6' sx={{ mb: 3 }}>Guest Information</Typography>
              <Grid container spacing={3}>
                <Grid item xs={12}>
                  <TextField fullWidth label='Full Name *' value={fullName} onChange={(e) => setFullName(e.target.value)} required />
                </Grid>
                <Grid item xs={12} sm={6}>
                  <TextField fullWidth label='Email *' type='email' value={email} onChange={(e) => setEmail(e.target.value)} required />
                </Grid>
                <Grid item xs={12} sm={6}>
                  <TextField fullWidth label='Phone Number' value={phone} onChange={(e) => setPhone(e.target.value)} />
                </Grid>
                <Grid item xs={12}>
                  <TextField
                    fullWidth
                    multiline
                    rows={3}
                    label='Special Requests (Optional)'
                    placeholder='Any special requests or preferences?'
                    value={specialRequests}
                    onChange={(e) => setSpecialRequests(e.target.value)}
                  />
                </Grid>
              </Grid>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={4}>
          <Card sx={{ position: 'sticky', top: 20 }}>
            <CardContent>
              <Typography variant='h6' sx={{ mb: 2 }}>Booking Summary</Typography>
              <Box sx={{ display: 'flex', gap: 2, mb: 2, pb: 2, borderBottom: 1, borderColor: 'divider' }}>
                <CardMedia component="img" sx={{ width: 80, height: 80, borderRadius: 1 }} image={hotel.image} alt={hotel.name} />
                <Box>
                  <Typography variant='subtitle2' sx={{ fontWeight: 600 }}>{hotel.name}</Typography>
                  <Typography variant='caption' color='text.secondary'>{hotel.location}</Typography>
                  <Rating value={hotel.rating} size="small" readOnly sx={{ mt: 0.5 }} />
                </Box>
              </Box>
              
              <Box sx={{ mb: 2 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                  <Typography variant='body2' color='text.secondary'>Check-in</Typography>
                  <Typography variant='body2'>{checkInDate.toLocaleDateString()}</Typography>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                  <Typography variant='body2' color='text.secondary'>Check-out</Typography>
                  <Typography variant='body2'>{checkOutDate.toLocaleDateString()}</Typography>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                  <Typography variant='body2' color='text.secondary'>Guests</Typography>
                  <Typography variant='body2'>{guestsCount} guests</Typography>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                  <Typography variant='body2' color='text.secondary'>Nights</Typography>
                  <Typography variant='body2'>{nights} nights</Typography>
                </Box>
              </Box>

              <Divider sx={{ my: 2 }} />

              {selectedRoomData && (
                <Box sx={{ mb: 2 }}>
                  <Typography variant='subtitle2' sx={{ fontWeight: 600, mb: 1 }}>Room Details</Typography>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                    <Typography variant='body2'>{selectedRoomData.type}</Typography>
                    <Typography variant='body2'>${selectedRoomData.price}/night</Typography>
                  </Box>
                </Box>
              )}

              <Divider sx={{ my: 2 }} />

              <Box sx={{ mb: 3 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                  <Typography variant='body2'>Room Total</Typography>
                  <Typography variant='body2'>${selectedRoomData ? selectedRoomData.price * nights : 0}</Typography>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                  <Typography variant='body2'>Taxes & Fees</Typography>
                  <Typography variant='body2'>Included</Typography>
                </Box>
                <Divider sx={{ my: 1 }} />
                <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                  <Typography variant='h6'>Total</Typography>
                  <Typography variant='h6' sx={{ color: 'primary.main', fontWeight: 600 }}>${totalPrice}</Typography>
                </Box>
              </Box>

              <Button
                fullWidth
                variant='contained'
                size='large'
                onClick={handleConfirmBooking}
                disabled={isLoading || !selectedRoom}
              >
                {isLoading ? 'Processing...' : `Confirm Booking - $${totalPrice}`}
              </Button>

              <Alert severity="info" sx={{ mt: 2 }}>
                Free cancellation up to 24 hours before check-in
              </Alert>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  )
}

export default HotelBooking