const BookingConfirmationPage = () => {
  const [formData, setFormData] = useState({
    name: '',
    email: '',
    phone: '',
    serviceType: 'standard',
    cost: 0,
    pickupLocation: { lat: -34.397, lng: 150.644 },
    destinationLocation: null,
  })

  const [isSubmitting, setIsSubmitting] = useState(false)
  const [errorMessage, setErrorMessage] = useState('')
  const router = useRouter()
  const params = useParams()
  const authentication = useAuthentication()
  const userId = authentication.user?.id
  const { enqueueSnackbar } = useSnackbar()
  const [booking, setBooking] = useState<Model.Booking | null>(null)
  const [isEditing, setIsEditing] = useState(false)
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)

  const handleInputChange = useCallback((e) => {
    const { name, value } = e.target
    setFormData((prevData) => ({
      ...prevData,
      [name]: value,
    }))
  }, [])

  const handleSubmit = useCallback(
    async (e) => {
      e.preventDefault()
      setIsSubmitting(true)
      setErrorMessage('')

      try {
        await Api.Booking.createOne(formData)
        router.push('/thank-you')
      } catch (error) {
        setErrorMessage('There was an issue with your booking. Please try again.')
      } finally {
        setIsSubmitting(false)
      }
    },
    [formData, router]
  )

  useEffect(() => {
    if (!params.bookingId) return

    const fetchBooking = async () => {
      try {
        const bookingData = await Api.Booking.findOne(params.bookingId, {
          includes: ['user'],
        })
        setBooking(bookingData)
        form.setFieldsValue({
          serviceType: bookingData.serviceType,
          name: bookingData.name,
          email: bookingData.email,
          phone: bookingData.phone,
          vehicleBrand: bookingData.vehicleBrand,
          vehicleModel: bookingData.vehicleModel,
          dateTime: dayjs(bookingData.dateTime),
        })
        setIsEditing(true)
      } catch (error) {
        enqueueSnackbar('Failed to fetch booking details', {
          variant: 'error',
        })
      }
    }

    fetchBooking()
  }, [params.bookingId, form, enqueueSnackbar])

  const handleEdit = useCallback(
    async (values) => {
      try {
        const updatedBooking = await Api.Booking.updateOne(params.bookingId, {
          ...values,
          dateTime: values.dateTime.toISOString(),
        })
        setBooking(updatedBooking)
        setIsEditing(false)
        enqueueSnackbar('Booking details updated successfully', {
          variant: 'success',
        })
      } catch (error) {
        enqueueSnackbar('Failed to update booking details', {
          variant: 'error',
        })
      }
    },
    [params.bookingId, enqueueSnackbar]
  )

  const handleEmailSend = useCallback(async () => {
    try {
      await Api.Notification.createOneByUserId(userId, {
        title: 'Booking Confirmation',
        message: `Your booking details: ${JSON.stringify(booking, null, 2)}`,
        userId: userId,
      })
      enqueueSnackbar('Booking details sent via email', { variant: 'success' })
    } catch (error) {
      enqueueSnackbar('Failed to send booking details via email', {
        variant: 'error',
      })
    }
  }, [userId, booking, enqueueSnackbar])

  const handleProceedToPayment = useCallback(() => {
    router.push('/payment')
  }, [router])

  useEffect(() => {
    const loader = new Loader({
      apiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY,
      version: 'weekly',
    })

    loader.load().then(() => {
      new google.maps.Map(document.getElementById('map'), {
        center: formData.pickupLocation,
        zoom: 8,
      })
    })
  }, [formData.pickupLocation])

  return (
    <PageLayout layout="narrow">
      <Title level={2}>Booking Confirmation</Title>
      <Text>Review and confirm your booking details below:</Text>
      <Card style={{ marginTop: 20 }}>
        {isEditing ? (
          <Form form={form} onFinish={handleEdit} layout="vertical">
            {/* Form fields here */}
            <Form.Item label="Pickup Location">
              <div id="map" style={{ height: '400px', width: '100%' }}></div>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                Save
              </Button>
              <Button
                type="default"
                onClick={() => setIsEditing(false)}
                style={{ marginLeft: 10 }}
              >
                Cancel
              </Button>
            </Form.Item>
          </Form>
        ) : (
          <div>
            {/* Booking details display */}
            <Button
              type="primary"
              icon={<EditOutlined />}
              onClick={() => setIsEditing(true)}
              style={{ marginTop: 20 }}
            >
              Edit
            </Button>
          </div>
        )}
      </Card>
      <Space style={{ marginTop: 20 }}>
        <Button
          type="primary"
          icon={<MailOutlined />}
          onClick={handleEmailSend}
        >
          Send Email
        </Button>
        <Button
          type="primary"
          icon={<CreditCardOutlined />}
          onClick={handleProceedToPayment}
        >
          Proceed to Payment
        </Button>
      </Space>
    </PageLayout>
  )
}

export default BookingConfirmationPage