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 Typography from '@mui/material/Typography'
import Button from '@mui/material/Button'
import Divider from '@mui/material/Divider'
import IconButton from '@mui/material/IconButton'
import TextField from '@mui/material/TextField'
import Alert from '@mui/material/Alert'
import Chip from '@mui/material/Chip'

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

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

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

interface FlightBookingProps {
  id: string
}

const FlightBooking = ({ id }: FlightBookingProps) => {
  const router = useRouter()
  const { passengers, isRoundTrip } = router.query
  const [flight, setFlight] = useState<any>(null)
  const [fullName, setFullName] = useState('')
  const [email, setEmail] = useState('')
  const [phone, setPhone] = useState('')
  const [isLoading, setIsLoading] = useState(false)

  useEffect(() => {
    const foundFlight = flights.find(f => f.id === id)
    setFlight(foundFlight)
  }, [id])

  if (!flight) return null

  const passengerCount = parseInt(passengers as string) || 1
  const roundTrip = isRoundTrip === 'true'
  const totalPrice = flight.price * passengerCount * (roundTrip ? 2 : 1)

  const handleConfirmBooking = () => {
    if (!fullName || !email) {
      toast.error('Please fill in your details')
      return
    }
    
    setIsLoading(true)
    setTimeout(() => {
      toast.success(`Flight 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 Flight Booking</Typography>
      </Box>

      <Grid container spacing={4}>
        <Grid item xs={12} md={8}>
          <Card sx={{ mb: 4 }}>
            <CardContent>
              <Typography variant='h6' sx={{ mb: 3 }}>Flight Details</Typography>
              <Box sx={{ p: 2, bgcolor: 'action.hover', borderRadius: 2 }}>
                <Grid container spacing={2}>
                  <Grid item xs={12} md={4}>
                    <Typography variant='caption' color='text.secondary'>Airline</Typography>
                    <Typography variant='h6'>{flight.airline}</Typography>
                    <Typography variant='caption'>{flight.flightNumber}</Typography>
                  </Grid>
                  <Grid item xs={12} md={8}>
                    <Grid container alignItems="center">
                      <Grid item xs={5}>
                        <Typography variant='h5'>{flight.departureTime}</Typography>
                        <Typography variant='body2'>{flight.from} ({flight.fromCode})</Typography>
                        <Typography variant='caption'>{flight.departureDate}</Typography>
                      </Grid>
                      <Grid item xs={2} sx={{ textAlign: 'center' }}>
                        <Icon icon='tabler:plane' />
                        <Typography variant='caption'>{flight.duration}</Typography>
                        {flight.stops === 0 ? (
                          <Chip label="Direct" size="small" color="success" sx={{ mt: 0.5 }} />
                        ) : (
                          <Chip label={`${flight.stops} stop`} size="small" sx={{ mt: 0.5 }} />
                        )}
                      </Grid>
                      <Grid item xs={5} sx={{ textAlign: 'right' }}>
                        <Typography variant='h5'>{flight.arrivalTime}</Typography>
                        <Typography variant='body2'>{flight.to} ({flight.toCode})</Typography>
                        <Typography variant='caption'>{flight.arrivalDate}</Typography>
                      </Grid>
                    </Grid>
                  </Grid>
                </Grid>
              </Box>
            </CardContent>
          </Card>

          <Card>
            <CardContent>
              <Typography variant='h6' sx={{ mb: 3 }}>Passenger 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>
            </CardContent>
          </Card>
        </Grid>

        <Grid item xs={12} md={4}>
          <Card sx={{ position: 'sticky', top: 20 }}>
            <CardContent>
              <Typography variant='h6' sx={{ mb: 2 }}>Price Summary</Typography>
              
              <Box sx={{ mb: 2 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                  <Typography variant='body2'>Base Fare</Typography>
                  <Typography variant='body2'>${flight.price}</Typography>
                </Box>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                  <Typography variant='body2'>x {passengerCount} passenger(s)</Typography>
                  <Typography variant='body2'>${flight.price * passengerCount}</Typography>
                </Box>
                {roundTrip && (
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                    <Typography variant='body2'>Return Flight</Typography>
                    <Typography variant='body2'>${flight.price * passengerCount}</Typography>
                  </Box>
                )}
              </Box>

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

              <Box sx={{ mb: 3 }}>
                <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}
              >
                {isLoading ? 'Processing...' : `Confirm Booking - $${totalPrice}`}
              </Button>

              <Alert severity="info" sx={{ mt: 2 }}>
                24-hour free cancellation policy applies
              </Alert>
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box>
  )
}

export default FlightBooking